# Why this code returns error?

**URL:** <https://www.ruby-forum.com/t/why-this-code-returns-error/61069>\
**Category:** Ruby\
**Created:** [May 19, 2006, 9:20pm UTC](https://www.ruby-forum.com/t/why-this-code-returns-error/61069 "2006-05-19T21:20:57Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![alan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a87d85/32.png) [@alan](https://www.ruby-forum.com/u/alan)\
**Post date:** [May 19, 2006, 9:20pm UTC](https://www.ruby-forum.com/t/why-this-code-returns-error/61069/1 "2006-05-19T21:20:57Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a87d85/32.png) [@alan](https://www.ruby-forum.com/u/alan)\
**Post date:** [May 19, 2006, 9:33pm UTC](https://www.ruby-forum.com/t/why-this-code-returns-error/61069/2 "2006-05-19T21:33:18Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a87d85/32.png) [@alan](https://www.ruby-forum.com/u/alan)\
**Post date:** [May 19, 2006, 9:51pm UTC](https://www.ruby-forum.com/t/why-this-code-returns-error/61069/3 "2006-05-19T21:51:23Z")

</div>

Thank you Daniel.

---

<div class="post-metadata">

**Author:** ![alan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a87d85/32.png) [@alan](https://www.ruby-forum.com/u/alan)\
**Post date:** [May 19, 2006, 11:14pm UTC](https://www.ruby-forum.com/t/why-this-code-returns-error/61069/4 "2006-05-19T23:14:57Z")

</div>

Alan wrote:

> Thank you Daniel.

No problem at all 🙂
