How can I convert an entire input string to an integer in Ruby?
I want to give Ruby integer input like this:
12 343 12312 12312 123123 231
12 343 12312 12312 123123 243
12 343 12312 12312 123123 2123
All of this should be taken as a number so that I can sort them all, and if there are any duplicate numbers I want to print them. The entire string must be treated as an integer for comparison with other strings. I cannot accept input in one integer, for each of these lines it gives me 12. How can I do this?
0
source to share
3 answers
The following snippet will display each number separately and print any duplicates. To check each line instead of individual numbers, uncomment the extra line.
str = <<STRING
12 343 12312 12312 123123 231
12 343 12312 12312 123123 243
12 343 12312 12312 123123 2123
STRING
nums = str.split(/\s/m).collect {|i| i.to_i}
#nums = str.gsub(/ /,'').collect {|i| i.to_i}
uniq_nums = nums.uniq.sort
uniq_nums.each do |uniq|
puts uniq if nums.find_all {|num| uniq == num}.length > 1
end
Return:
12 343 12312 123123
0
source to share