Last Updated
Viewed 51 Times

Lately I saw this function signature:

   class Foo < Bar
    def initialize(arg: {})
      ...
   end

What does the keyword argument (arg: {} ) with the curly braces means here?

Similar Question 1 : Ruby required keyword arguments

For Ruby methods, the required keyword syntax is nice

def foo(bar:, baz:)
  :
end

foo(:bar => true, :baz => false) # OK
foo(:bar => true) # missing keyword argument error

Can one 'splat' the list of required keywords with some kind of magic? i.e.,

required_keywords = [:bar, :baz]
def foo(magic(required_keywords))
  :
end

I expect not, but I'm often surprised with what Ruby can be persuaded to do.

Just trying to understand how to collect arguments in Ruby, I came up with the following snippet, that seems to fail to collect keyword arguments in **kargs in some case:

def foo(i, j= 9, *args, k: 11, **kargs)
  puts "args: #{args}; kargs: #{kargs}"
end

foo(a: 7, b: 8)
# output: args: []; kargs: {}
foo(9, a: 7, b: 8)
# output: args: []; kargs: {:a=>7, :b=>8}
foo(9, 10, 13, a: 7, b: 8)
# output: args: [13]; kargs: {:a=>7, :b=>8}

I would like to know why it does not collect kargs in the first call to foo, while in the second call it does.

If we have a create_widget method defined this way:

def create_widget(size, properties)
  puts properties.class #=> Hash
  puts properties[:id] #=> table22
end

What is the difference between:

create_widget(6, {:id => "table22", :class => "Cart"})
create_widget(6, :id => "table22", :class => "Cart")
create_widget(6, id: "table22", class: "Cart")

In any cases, the second argument is a Hash, and renders the same result.

Similar Question 4 (1 solutions) : Ruby keyword arguments best practice

Similar Question 5 (3 solutions) : Keyword arguments unpacking (splat) in Ruby

Similar Question 7 (2 solutions) : Does ruby 1.9.3 have keyword arguments?

cc