Code block passed to each works with brackets but not with ‘do’-‘end’ (ruby)

puts mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end

Here you called puts without parens, the do ... end refers to the puts method, that does nothing with a block and prints mystring.gsub(art[0]).each (with is a Enumerator).

The { ... } is called with the nearest method. Becomes ugly, but you can do it with do ... end:

puts(mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end)

Or, better, put the result in a variable and print the variable:

var = mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end
puts var

Anyway, the each don’t changes the object, it just iterate and returns the object itself. You may be wanting the map method, test it.

Leave a Comment