I have found a question: Nested Loops Ruby and solved it, but the solution looks ugly (although works):
puts (1..10).map { |i| (i..10).step(i).inject(0) { |memo, obj| memo = memo | 2**(obj-1) } }.inject(0) { |memo, obj| memo = memo ^ obj}
Rewritten to multiline, but keeping curly braces:
puts (1..10).map { |i|
(i..10).step(i).inject(0) { |memo, obj|
memo = memo | 2**(obj-1)
}
}.inject { |memo, obj|
memo = memo ^ obj
}
I tried to rewrite it into multiline do-end blocks to make it more readable (knowing about the precedence difference between {} and do-end), but I get an error (I just changed the last braces):
puts (1..10).map { |i|
(i..10).step(i).inject(0) { |memo, obj|
memo = memo | 2**(obj-1)
}
}.inject do |memo, obj|
memo = memo ^ obj
end.to_s(2)
../../bitflipping.rb:5:in 'each': no block given (LocalJumpError)
from ../../bitflipping.rb:5:in 'inject'
from ../../bitflipping.rb:5:in ''
Is it possible to rewrite this with do-end? I think there is a precedence problem, how can I regroup them so for example inject at the end gets the block properly?
try making it into a method, maybe? although as sawa says,
map{|x| x}doesn't do anything