Why this code returns error?

Hi,

Why this line gives me error?

File.open(“test.rb”).grep /.*$/ {|line| print line }

I changed it from the following form:

File.open(“test.rb”).grep /.*$/ do |line|
print line
end

Alan wrote:

File.open(“test.rb”).grep /.*$/ {|line| print line }

I changed it from the following form:

File.open(“test.rb”).grep /.*$/ do |line|
print line
end

It’s because the precedence of curly bracket blocks ( {} ) and do/end
blocks are not the same.

File.open(“test.rb”).grep /.*$/ {|line| puts line }

is the same as

File.open(“test.rb”).grep(/.*$/ {|line| puts line })

which means that the block is actually attached to `/.*$/’, not #grep.
That’s what gives you the error.

File.open(“test.rb”).grep /.*$/ do |line|
print line
end

is the same as

File.open(“test.rb”).grep(/.*$/) {|line| puts line }

which is probably what you want.

Daniel

Thank you Daniel.

Alan wrote:

Thank you Daniel.

No problem at all :slight_smile: