Ruby doesn't have keyword argument passing. (Not yet, anyway, it is one of the things that might make it into Ruby 2.0. However, there are no guarantees, and work on Ruby 2.0 hasn't even started yet, so there's no telling when or even if we will see keyword arguments in Ruby.)
What really happens, is this: you are passing the expression arg2 = 4
as the only argument in the argument list. Ruby is a strict language with pass-by-value, which means that all arguments are fully evaluated before they are passed to the method. In this case, arg2 = 4
is an assignment expression (in Ruby, everything is an expression (i.e. everything returns a value), there are no statements). You are assigning the immediate literal Fixnum
value 4
to the local variable arg2
. Assignment expressions always return the value of their right-hand side, in this case 4
.
So, you are passing the value 4
as the only argument into your method, which means that it gets bound to the first mandatory parameter if there is one (in this case, there isn't), otherwise to the first optional parameter (in this case arg1
).
The usual way to deal with situations like this is to use a Hash
instead, like this:
some_method({:arg2 => 4})
Because this pattern is used so often, there is special syntactic support: if the last argument to a method is a Hash
, you can leave off the curly braces:
some_method(:arg2 => 4)
In Ruby 1.9, there is another syntactical convenience form: because Hash
es are so often used with Symbol
keys, there is an alternative Hash
literal syntax for that:
some_method({arg2: 4})
Combine them both, and you almost have keyword arguments:
some_method(arg2: 4)
(In fact, both of these shortcuts were specifically added to provide an easy migration path towards possible future versions of Ruby with keyword arguments.)
MacRuby actually supports Smalltalk-style multipart message selectors for interoperability with Objective-C. Note, however, that Smalltalk-style multipart message selectors are not keyword arguments, they behave very differently. Also, of course, this extension is specific to MacRuby and not part of the Ruby Specification and not portable to MRI, YARV, JRuby, XRuby, IronRuby, MagLev, Rubinius, tinyrb, RubyGoLightly, BlueRuby, SmallRuby or any other Ruby Implementation.