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

···

--
Posted via http://www.ruby-forum.com/.

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.

···

--
Posted via http://www.ruby-forum.com/.

Alan wrote:

Thank you Daniel.

No problem at all :slight_smile: