๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Keyword Arguments

Keyword arguments give each value a name in the method definition. A call then passes values by name in any order.

Naming arguments at the call

Each parameter ends with a colon in the definition. The call passes each value with its name, so the order can change.

def book(title:, author:)
  puts "#{title} by #{author}"
end
book(title: "Dune", author: "Herbert")
book(author: "Herbert", title: "Dune")

A keyword with a default

The greeting keyword carries a default value. A call can leave it out or pass its own value.

def greet(name:, greeting: "Hello")
  puts "#{greeting}, #{name}"
end
greet(name: "Ana")
greet(name: "Ben", greeting: "Hi")

A plain parameter beside keywords

A plain parameter still takes its value by position. The keyword after it takes its value by name.

def label(text, size: 12)
  puts "#{text} at size #{size}"
end
label("Sale")
label("Sale", size: 20)

Gathering unnamed keywords

The **extras parameter gathers keywords the method did not name. They arrive as one hash of symbol keys.

def order(item:, **extras)
  p extras
  puts item
end
order(item: "pen", color: "blue", count: 3)

Example

def make_card(name:, occasion: "birthday")
  puts "Happy #{occasion}, #{name}!"
end
make_card(name: "Ana")
make_card(name: "Ben", occasion: "anniversary")

Key points

  • A parameter written as name: is a keyword parameter.
  • A keyword with no default is required at every call.
  • A keyword with a default uses that value when the call leaves it out.
  • Calls can list keywords in any order and still fill the right parameters.
  • Two stars before a name gather the keywords a method did not name.

In this example, name is a required keyword and occasion carries a default. The first call leaves occasion out, so the default birthday fills it. The second call passes its own occasion by name.

Note

A gathered keyword hash prints its keys as symbols.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A method is defined as def ship(city:, speed: "slow"). Which call runs without an error?