Defining <<

L

Luke Ivers

I'm not 100% how exactly to search to find out if someone else has posed
this question, but why does the following happen?

Given:

class Hash
def << (key, val=nil)
self.store(key, val)
end
end

h = {}
h << 'test'
h << 'test', 'bob'

Gives back:

test.rb:9: parse error, unexpected ',', expecting $
h << 'test', 'bob'

If I change the last line to:

h << ('test', 'bob')

I get back:

test.rb:9: parse error, unexpected ',', expecting ')'
h << ('test', 'bob')
 
G

Gary Wright

I'm not 100% how exactly to search to find out if someone else has
posed
this question, but why does the following happen?

Given:

class Hash
def << (key, val=nil)
self.store(key, val)
end
end

h = {}
h << 'test'
h << 'test', 'bob'

The syntax rules for the << operator don't allow it to take multiple
arguments when called via infix notation:

h << arg1 # one argument only

you can call the method with multiple arguments but you've got to do
it like:

h.<<(arg1, arg2) # dot-style method invocation

You can use an array to 'cheat':

h << [arg1, arg2]

But the method will only see one argument, an array, and you would have
to expect that and/or test for it in your definition for Hash#<<.

Gary Wright
 
R

Robert Klemme

I'm not 100% how exactly to search to find out if someone else has posed
this question, but why does the following happen?

Given:

class Hash
def << (key, val=nil)
self.store(key, val)
end
end

h = {}
h << 'test'
h << 'test', 'bob'

The syntax rules for the << operator don't allow it to take multiple
arguments when called via infix notation:

h << arg1 # one argument only

you can call the method with multiple arguments but you've got to do it
like:

h.<<(arg1, arg2) # dot-style method invocation

You can use an array to 'cheat':

h << [arg1, arg2]

But the method will only see one argument, an array, and you would have
to expect that and/or test for it in your definition for Hash#<<.

Here's another variant:

class Hash
Proxy = Struct.new :parent, :key do
def <<(val)
parent[key] = val
parent
end
end
def <<(key)
Proxy.new self, key
end
end

irb(main):012:0> h ={}
=> {}
irb(main):013:0> h << "foo" << "bar" << "key" << 234
=> {"foo"=>"bar", "key"=>234}
irb(main):014:0> h << 2 << 3
=> {2=>3, "foo"=>"bar", "key"=>234}
irb(main):015:0> h
=> {2=>3, "foo"=>"bar", "key"=>234}

Not that I would recommend it...

Kind regards

robert
 
S

Simon Kröger

Robert said:
[...]
irb(main):013:0> h << "foo" << "bar" << "key" << 234
[...]

Not that I would recommend it...

Yeah, i like

h <= "foo" > "bar" <= "key" > 42

:)

unfortunately there is no => operator...

cheers

Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,232
Messages
2,571,168
Members
47,803
Latest member
ShaunaSode

Latest Threads

Top