Keyword Argument di Ruby 2
- Categories:
- ruby
Dimulai dari Ruby 2.0, Ruby menyediakan fitur keyword argument.
# Sebelum Ruby 2.0
def hello(options = {})
foo = options.fetch(:foo, "bar")
puts foo
end
hello # => bar
hello(foo: "world") # => world
# Ruby 2.0 keatas
def hello(foo: "bar")
puts foo
end
hello # => bar
hello(foo: "world") # => world
Block pada Ruby 2 juga dapat menerima keyword argument.
# 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
Argument Error Handler
Ruby 2.0 tidak memiliki built-in support ketika ada argument error pada keyword argument. Pada Ruby 2.1 fitur tersebut mulai diperkenalkan.
def hello(foo:)
puts foo
end
hello # => ArgumentError: missing keyword: foo
hello(foo: "bar") # => bar
Kelebihan Method Dengan Keyword Argument
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.
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
- Tags:
- #ruby