On Fri, Apr 5, 2013 at 10:32 PM, Wins Lin <lists / ruby-forum.com> wrote:

> I have a code:
>
> module Foo
>   class Config
>     attr_reader :config
>
>     def initialize
>       @config = {}  <-- standard hash
>     end
>
>     def <<(key, val)   <-- I want to implement "<<" sign as a method
> name
>

That does not work.  You can only pass in one value (see below).

For your use case better implement []= operator.


>       n_hash = {key => val}
>       if (@config.merge!(n_hash))
>         return true
>       else
>         return false
>       end
>

That's quite a complicated way to convert a boolean (result of #merge!)
into a boolean.  The whole if else end construction is superfluous.  And it
won't work, too, because Hash#merge! always returns self.

irb(main):001:0> h={}
=> {}
irb(main):002:0> h.merge! 1=>2
=> {1=>2}
irb(main):003:0> h.merge! 1=>2
=> {1=>2}
irb(main):004:0> h.merge!({})
=> {1=>2}



>     end
>
>   end
> end
>
>
>
> Now I call it:
>
> c = Foo::Config.new
>
> c << "name", "value"   <- This doesn't work. ...syntax error, unexpected
> ',', expecting ')'
>
> c.<<("name", "value")  <- this works. But it's ridiculous such a call in
> Ruby.
>
> Why
> c << "name", "value"
> doesn't work?


Because << is a binary operator: arg1 op arg2 - that's the way code is
parsed, i.e. it's defined in the syntax.  With the parentheses you made it
an explicit method call, which works.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/