Last active
December 20, 2015 10:49
-
-
Save mistydemeo/6118071 to your computer and use it in GitHub Desktop.
Keyword arguments in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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