0

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?

Pesto
  • 23,810
  • 2
  • 71
  • 76
Hick
  • 35,524
  • 46
  • 151
  • 243
  • 1
    Are you saying you want to strip the spaces out and leave just the numbers, so '12 343' becomes '12343'? – ceejayoz May 28 '09 at 17:28

3 Answers3

6

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
  • 19,959
  • 4
  • 61
  • 86
1

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
  • 23,810
  • 2
  • 71
  • 76
0

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
  • 73
  • 1
  • 5
  • u didnt understand my question .. !! 12 231 1231 1231 212 is one whole integer input and 12 231 1231 1231 211 is another input then i have to sort – Hick May 31 '09 at 18:59
  • 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 Jun 01 '09 at 20:00