I recently started learning ruby, and I understood that you coud use code blocks with both of these syntaxes. But I just found a case which I dont understand:
#my_hash is a hash in which the keys are strings and the values arrays, but dont think about the specifics fo the code
#if I run my code like this, it works perfectly
my_hash.each do |art|
puts mystring.gsub(art[0]).each {
art[1][rand(art[1].length) -1]
}
end
#but if I use this, it prints "Enumerator"
my_hash.each do |art|
puts mystring.gsub(art[0]).each do
art[1][rand(art[1].length) -1]
end
end
Is it because you cant nest do-end pairs?
I am using 1.9
Here you called
putswithout parens, thedo ... endrefers to theputsmethod, that does nothing with a block and printsmystring.gsub(art[0]).each(with is aEnumerator).The
{ ... }is called with the nearest method. Becomes ugly, but you can do it withdo ... end:Or, better, put the result in a variable and print the variable:
Anyway, the
eachdon’t changes the object, it just iterate and returns the object itself. You may be wanting themapmethod, test it.