Skip to content

Instantly share code, notes, and snippets.

@mistydemeo
Last active December 20, 2015 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mistydemeo/6118071 to your computer and use it in GitHub Desktop.
Save mistydemeo/6118071 to your computer and use it in GitHub Desktop.
Keyword arguments in Ruby
# 1.9.x and earlier don't support keyword arguments, but you can pass hashes as arguments
def function(hsh)
return hsh[:a] == hsh[:b]
end
function :a => :foo, :b => :bar #=> false
# The syntax is actually just a bit of syntactic sugar for passing a hash without enclosing braces.
# All of these are the same thing:
function :a => :foo, :b => :bar
function a: :foo, b: :bar
function({:a => :foo, :b => :bar})
hsh = {:a => :foo, :b => :bar}; function(hsh)
# 2.0 added official syntax for keyword arguments, with default values
def function(a: :default, b: :default)
return a == b
end
function :a => :foo, :b => :bar #=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment