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

hello # => alohahello(foo: “world”) # => world

# Ruby 2.0 keatasdef hello(foo: “aloha”) puts fooend

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

# 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

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

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 Argumentdef 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 perubahanmy_method(first: “hello”, second: “foo”, third: “bar”) # => hello — foo — bar

Sumber

Leave a comment