Keyword Argument Pada Ruby
Dimulai dari Ruby 2.0, Ruby menyediakan fitur keyword argument.
[code language=”ruby”]
# Sebelum Ruby 2.0
def hello(options = {})
foo = options.fetch(:foo, “aloha”)
puts foo
end
hello # => aloha
hello(foo: “world”) # => world
# Ruby 2.0 keatas
def hello(foo: “aloha”)
puts foo
end
hello # => aloha
hello(foo: “world”) # => world
[/code]
Block pada Ruby 2 juga dapat menerima keyword argument.
[code language=”ruby”]
# Sebelum Ruby 2.0
define_method :hello do |options = {}|
foo = options.fetch(:foo, “bar”)
puts foo
end
# Ruby 2.0 keatas
define_method(:hello) do |foo: ‘bar’|
puts foo
end
[/code]
Ruby 2.0 tidak memiliki built-in support ketika ada argument error pada keyword argument. Pada Ruby 2.1 fitur tersebut mulai diperkenalkan.
[code language=”ruby”]
def hello(foo:)
puts foo
end
hello # => ArgumentError: missing keyword: foo
hello(foo: “aloha”) # => aloha
[/code]
Salah satu kelebihan utama method dengan keyword argument adalah method pada caller tidak lagi harus mengetahui urutan argumen atau parameter saat melakukan pemanggilan method.
Dengan begitu ketika argumen pada method bertukar posisi, pada caller tidak diperlukan perubahan kode.
[code language=”ruby”]
def my_method(first, second, third)
puts “#{first} — #{second} — #{third}”
end
my_method(“hello”, “foo”, “bar”) # => hello — foo — bar
def my_method(first, third, second)
puts “#{first} — #{second} — #{third}”
end
my_method(“hello”, “foo”, “bar”) # => hello — bar — foo
# Dengan Keyword Argument
def my_method(first:, second:, third:)
puts “#{first} — #{second} — #{third}”
end
my_method(first: “hello”, second: “foo”, third: “bar”) # => hello — foo — bar
def my_method(first:, third:, second:)
puts “#{first} — #{second} — #{third}”
end
# caller tidak mengalami perubahan
my_method(first: “hello”, second: “foo”, third: “bar”) # => hello — foo — bar
[/code]