Forum: Ruby Why this code returns error?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A5735ac216e523d16f3a238fb547ae7e?d=identicon&s=25 Alan (Guest)
on 2006-05-19 21:20
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
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-19 21:33
(Received via mailing list)
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
A5735ac216e523d16f3a238fb547ae7e?d=identicon&s=25 Alan (Guest)
on 2006-05-19 21:51
Thank you Daniel.
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-19 23:14
(Received via mailing list)
Alan wrote:
> Thank you Daniel.

No problem at all :)
This topic is locked and can not be replied to.