简体   繁体   English

是否可以在Ruby中访问关键字参数作为哈希?

[英]Is it possible to get access to keyword arguments as a Hash in Ruby?

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; ... 但是有可能写一些更短的而不是@x = x; @y = y; ... @x = x; @y = y; ... @x = x; @y = y; ... to initialize instance variables from passed keyword arguments? @x = x; @y = y; ...从传递的关键字参数初始化实例变量? Is it possible to get access to passed keyword arguments as a Hash? 是否可以将传递的关键字参数作为哈希访问?

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 . 不是我建议使用的东西(因为eval !),但这是我能想到的唯一方法,因为我认为没有办法获得没有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. method返回传入符号的Method对象, __method__返回当前方法的名称, Method#parameters返回描述方法接受的参数的数组。 Here I only set the parameters which have the type :key (named params). 这里我只设置具有类型的参数:key (名为params)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM