是否可以在 Ruby 中以哈希形式访问关键字参数? [英] Is it possible to get access to keyword arguments as a Hash in Ruby?

查看:29
本文介绍了是否可以在 Ruby 中以哈希形式访问关键字参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我能做到:

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).

所以我可以写:

class A
  def initialize(param1: 3, param2: 4)
    @param1 = param1
    @param2 = param2
  end
end

但是有没有可能写更短的东西而不是@x = x;@y = y;... 从传递的关键字参数初始化实例变量?是否可以访问作为哈希传递的关键字参数?

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?

推荐答案

我不推荐使用(因为 eval!),但这是我能想到的唯一方法,因为我不不认为有一种方法可以在没有 eval 的情况下获取局部变量的值.

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

输出:

#<A:0x007fd7e21008d0 @param1=20, @param2=23>
#<A:0x007fd7e2100218 @param1=3, @param2=4>

method 返回一个 Method 对象用于传入的符号,__method__ 返回当前方法的名称,Method#parameters 返回一个描述该方法接受的参数的数组.这里我只设置类型为:key(命名为params)的参数.

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).

这篇关于是否可以在 Ruby 中以哈希形式访问关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆