Keyword Argument Pada Ruby

Dimulai dari Ruby 2.0, Ruby menyediakan fitur keyword argument.

# Sebelum Ruby 2.0def hello(options = {}) foo = options.fetch(:foo, “aloha”) puts fooend</p><p>hello # => alohahello(foo: “world”) # => world</p><p># Ruby 2.0 keatasdef hello(foo: “aloha”) puts fooend</p><p>hello # => alohahello(foo: “world”) # => worldBlock pada Ruby 2 juga dapat menerima keyword argument.

# Sebelum Ruby 2.0define_method :hello do |options = {}| foo = options.fetch(:foo, “bar”) puts fooend</p><p># Ruby 2.0 keatasdefine_method(:hello) do |foo: ‘bar’| puts fooend

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 fooend</p><p>hello # => ArgumentError: missing keyword: foohello(foo: “aloha”) # => aloha

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</p><p>my_method(“hello”, “foo”, “bar”) # => hello — foo — bar</p><p>def my_method(first, third, second) puts “#{first} — #{second} — #{third}”end</p><p>my_method(“hello”, “foo”, “bar”) # => hello — bar — foo</p><p># Dengan Keyword Argumentdef my_method(first:, second:, third:) puts “#{first} — #{second} — #{third}”end</p><p>my_method(first: “hello”, second: “foo”, third: “bar”) # => hello — foo — bar</p><p>def my_method(first:, third:, second:) puts “#{first} — #{second} — #{third}”end</p><p># caller tidak mengalami perubahanmy_method(first: “hello”, second: “foo”, third: “bar”) # => hello — foo — bar

Sumber

Leave a Reply