0

Here is the code:

def count_ones(number, num_bits)
      (0...num_bits).inject(0) { |total, shift| total + (number >> shift & 1) }
end

puts (0...gets.to_i).map do 
    start, finish = gets.split.map(&:to_i)
    (start..finish).inject(0) { |total, number| total + count_ones(number, 32) }
end

If I input 3, I would expect to be able to input 3 more times. Instead it prints out an enumerable object..

But.. if I do this, and input 3 :

puts (0...gets.to_i).map { |i| i }

I get the result I'm expecting: 0 1 2

How can I reconcile these contradictory behaviors with one and other?

ordinary
  • 5,943
  • 14
  • 43
  • 60

1 Answers1

0

For anyone wondering, I figured it out: It was actually the usage of do/end as opposed to curly brackets. This code actually evaluates and prints the block how I expect it to:

def count_ones(number, num_bits)
      (0...num_bits).inject(0) { |total, shift| total + (number >> shift & 1) }
end

puts (0...gets.to_i).map {
    start, finish = gets.split.map(&:to_i)
    (start..finish).inject(0) { |total, number| total + count_ones(number, 32) }
}

Very interesting, because until now I had thought that curly brackets and do/end were semantically equivalent.

ordinary
  • 5,943
  • 14
  • 43
  • 60
  • 4
    It's because they have different precedence: http://stackoverflow.com/questions/2122380/using-do-block-vs-brackets – Jimmy Jul 10 '13 at 07:51
  • [Another question](http://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby) about the difference between `do..end` and `{..}`. – toro2k Jul 10 '13 at 07:57
  • Not only they differ in precedence. I had a question where I couldn't translate nested curly brace blocks into do/end blocks __at all__: http://stackoverflow.com/questions/20424778/ruby-curly-braces-vs-do-end-method-chaining – karatedog Jan 06 '14 at 17:33