I know I can do:
class Parent
def initialize(args)
args.each do |k,v|
instance_variable_set("@#{k}", v)
end
end
end
class A < Parent
def initialize(attrs)
super(attrs)
end
end
But I'd want to use keyword arguments to make more clear which hash keys method may accept (and have validation saying that this key isn't supported).
So I can write:
class A
def initialize(param1: 3, param2: 4)
@param1 = param1
@param2 = param2
end
end
But is it possible to write something shorter instead of @x = x; @y = y; ...
to initialize instance variables from passed keyword arguments? Is it possible to get access to passed keyword arguments as a Hash?
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
What are keyword arguments? Keyword arguments are a feature in Ruby 2.0 and higher. They're an alternative to positional arguments, and are really similar (conceptually) to passing a hash to a function, but with better and more explicit errors.
Not something I would recommend using (because eval
!), but this is the only way I can think of, as I don't think there's a way to get the value of a local variable without eval
.
class A
def initialize(param1: 3, param2: 4)
method(__method__).parameters.each do |type, name|
if type == :key
instance_variable_set "@#{name}", eval("#{name}")
end
end
end
end
p A.new param1: 20, param2: 23
p A.new
Output:
#<A:0x007fd7e21008d0 @param1=20, @param2=23>
#<A:0x007fd7e2100218 @param1=3, @param2=4>
method
returns a Method
object for the passed in symbol, __method__
returns the name of the current method, and Method#parameters
returns an array describing the parameters the method accepts. Here I only set the parameters which have the type :key
(named params).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With