|
def print_exception &block
|
|
begin
|
|
yield
|
|
rescue => e
|
|
puts "#{e.class}: #{e.message}"
|
|
end
|
|
end
|
|
|
|
def named_args(arg1:, arg2:)
|
|
puts arg1.inspect
|
|
puts arg2.inspect
|
|
end
|
|
|
|
named_args(arg1: :foo, arg2: :bar)
|
|
# :foo
|
|
# :bar
|
|
#=> nil
|
|
|
|
print_exception do
|
|
named_args(arg1: :foo, arg2: :bar, arg3: :asdf)
|
|
end
|
|
#ArgumentError: unknown keyword: arg3
|
|
|
|
args = {arg1: :foo, arg2: :bar}
|
|
#=> {:arg1=>:foo, :arg2=>:bar}
|
|
|
|
named_args(**args)
|
|
# :foo
|
|
# :bar
|
|
#=> nil
|
|
|
|
print_exception do
|
|
named_args(**args, arg3: :asdf)
|
|
end
|
|
#ArgumentError: unknown keyword: arg3
|
|
|
|
args
|
|
#=> {:arg1=>:foo, :arg2=>:bar, :arg3=>:asdf}
|
|
# Wtf? Why is there an arg3? I never set that.
|
|
|
|
require 'ostruct'
|
|
args = OpenStruct.new(**args)
|
|
#=> #<OpenStruct arg1=:foo, arg2=:bar, arg3=:asdf>
|
|
|
|
print_exception do
|
|
named_args(**args)
|
|
end
|
|
#TypeError: can't convert OpenStruct to Hash (OpenStruct#to_hash gives NilClass)
|
|
|
|
class << args
|
|
alias_method :to_hash, :to_h
|
|
end
|
|
|
|
print_exception do
|
|
named_args(**args)
|
|
end
|
|
#ArgumentError: unknown keyword: arg3
|
|
|
|
args.arg3
|
|
#=> :asdf
|
|
|
|
args.to_hash
|
|
#=> {:arg1=>:foo, :arg2=>:bar, :arg3=>:asdf}
|
|
|
|
named_args(**args, arg4: :wtf)
|
|
# (pry):19: [BUG] Segmentation fault at 0x00006c
|
|
# ruby 2.1.2p95 (2014-05-08 revision 45877) [i686-linux]
|