Python vs Ruby keyword arguments

I recently switched from working in Python to working in Ruby. The behavior of Ruby’s keyword arguments gave me a shock. You have to explicitly decide between positional and keyword arguments for methods in Ruby. With a method with keyword arguments, Ruby won’t interpret your parameters as positional if you don’t supply the parameter name. It will instead throw an argument error.

For example, in Python (examples from Stackoverflow):

def fn(a, b, c = 1):
    return a * b + c

print fn(1, 2)                # returns 3, positional and default.
print fn(1, 2, 3)             # returns 5, positional.
print fn(c = 5, b = 2, a = 2) # returns 9, named.
print fn(b = 2, a = 2)        # returns 5, named and default.
print fn(5, c = 2, b = 1)     # returns 7, positional and named.
print fn(8, b = 0)            # returns 1, positional, named and default.

In Ruby, for method with positional arguments:

def fn(a, b, c = 1)
    a * b + c
end

puts fn(1, 2)                # returns 3
puts fn(1, 2, 3)             # returns 5
puts fn(c: 5, b: 2, a: 2)    # ArgumentError, Wrong Number of Arguments
puts fn(b: 2, a: 2)          # ArgumentError, Wrong Number of Arguments
puts fn(5, c: 2, b: 1)       # ArgumentError, Wrong Number of Arguments
puts fn(8, b: 0)             # ArgumentError, Wrong Number of Arguments

For methods with keyword arguments:

def fn(a:, b:, c: 1)
    a * b + c
end

puts fn(1, 2)                # ArgumentError, Missing keywords
puts fn(1, 2, 3)             # ArgumentError, Missing keywords
puts fn(c: 5, b: 2, a: 2)    # returns 9
puts fn(b: 2, a: 2)          # returns 5
puts fn(5, c: 2, b: 1)       # ArgumentError, Missing keywords
puts fn(8, b: 0)             # ArgumentError, Missing keywords

Here’s a neat article on Ruby 2 arguments from thoughtbot.

Here’s a short FAQ on parameters vs arguments from Python 3.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: