tags:

views:

271

answers:

3

I want to give integer input to Ruby like this:

12 343 12312 12312 123123 231
12 343 12312 12312 123123 243
12 343 12312 12312 123123 2123

This whole thing should be taken as a number so that I can sort all of them and if there is any repeating numbers I want to print them. The whole line should be treated as an integer for comparison with the other lines. I am not able to take the input into one integer, for each of those lines it gives me 12. How can I accomplish this?

+6  A: 

If you want it all as one number, just use:

input.gsub(/\s/,'').to_i

If you want an array of ints, use

input.split.map{|i| i.to_i}
Chris Doggett
As best as I can tell, he wants each line as one number.
Pesto
My brain stopped trying to parse after 'dem', 'dat', and 'no.'
Chris Doggett
+1  A: 

This will keep accepting lines of input, remove all whitespace, convert it to a number, and add them to an array:

numbers = []
STDIN.each_line do |line|
  numbers << line.gsub(/\s+/, '').to_i
end
Pesto
A: 

The following snippet will take each of the numbers individually and print out any duplicates. To check each line instead of the 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

Returns:

12
343
12312
123123
ldfritz
u didnt understand my question .. !! 12 231 1231 1231 212 is one whole integer input and 12 231 1231 1231 211 is another inputthen i have to sort
mekasperasky
Like I mentioned in my initial post, the commented line of code will read each line of input as a single number. So, simply uncommenting it will give you the desired behavior.
ldfritz