Created
June 4, 2013 18:02
-
-
Save paulmooring/5708067 to your computer and use it in GitHub Desktop.
Ruby arguments
This file contains hidden or 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
# Function with 2 arguments and no default values | |
[1] pry(main)> def test(one, two) | |
[1] pry(main)* puts one | |
[1] pry(main)* puts two | |
[1] pry(main)* end | |
# Function with 2 arguments has a default value on 2 | |
[2] pry(main)> def test2(one, two="world!") | |
[2] pry(main)* puts one | |
[2] pry(main)* puts two | |
[2] pry(main)* end | |
# Function with 1 argument (uses a hash and defaults in the body) | |
[3] pry(main)> def test3(hsh) | |
[3] pry(main)* puts hsh[:one] | |
[3] pry(main)* puts (hsh[:two] || "world!") | |
[3] pry(main)* end | |
# Works with 2 args | |
[4] pry(main)> test "hello", "world!" | |
hello | |
world! | |
=> nil | |
# Errors with 1 arg | |
[5] pry(main)> test "hello" | |
ArgumentError: wrong number of arguments (1 for 2) | |
from (pry):1:in `test' | |
# Works with 1 arg | |
[6] pry(main)> test2 "hello" | |
hello | |
world! | |
=> nil | |
# ...or 2 args | |
[7] pry(main)> test2 "hello", "world!" | |
hello | |
world! | |
=> nil | |
# takes a hash (give it as many "args" as you want but they're name sensitive) | |
[8] pry(main)> test3 :one => "hello", :two => "there" | |
hello | |
there | |
=> nil | |
[9] pry(main)> test3 :one => "hello" | |
hello | |
world! | |
=> nil | |
[10] pry(main)> test3 :one => "hello", :three => "there", :four => "you" | |
hello | |
world! | |
=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment