[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-core
Subject:    Re: Attaching a block to []
From:       "David A. Black" <dblack () wobblini ! net>
Date:       2005-01-31 13:54:01
Message-ID: Pine.LNX.4.61.0501310547400.23698 () wobblini
[Download RAW message or body]

Hi --

On Mon, 31 Jan 2005, Brian Mitchell wrote:

> Hello,
>
> Talking to Tilman Sauerbeck on IRC lead me to an interesting bug in
> ruby. The following code gives a syntax error using both 1.8.2 and my
> recent build of 1.9:
>
> class Hash
>    alias_method :orig_lookup, :[]
>
>    def [](key)
>        value = self.orig_lookup(key)
>        block_given? ? (yield value) : value
>    end
> end
>
> Foo = { :key => :value }
>
> Foo[:key] do |v| # Syntax Error!
>    p v
> end
>
> As you can see the code is trying to yield the lookup on the hash
> table if a block was passed. Running the code will simply not let the
> block be passed unless you make this change:
>
> Foo.[](:key) do |v| # No syntax error.

I don't consider this a bug, but rather a consequence of having the []
method call fully masquerade as something other than a method call in
its syntax.

The same thing happens with <<:

   irb(main):022:0> str = ""
   => ""
   irb(main):023:0> str << "a" do end
   SyntaxError: compile error
   (irb):23: syntax error
   str << "a" do end
                ^
           from (irb):23
   irb(main):024:0> str.<<("a") do end
   => "a"

I think it's a case of: you can't have it both ways.  You can't have
the syntactic sugar/magic that enables these methods to look like
operators, and also the code-block syntax that goes with methods.  I
suspect this is a conscious design decision.


David

-- 
David A. Black
dblack@wobblini.net

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic