【问题标题】:How do i get the names or arguments inside the method definition? [duplicate]如何获取方法定义中的名称或参数? [复制]
【发布时间】:2011-08-21 06:53:54
【问题描述】:

有没有办法获取方法中的参数名称列表?

例如,假设我有以下方法定义:

def speak(name, age, address)
  # some code
end

如何获得nameageaddress 的数组?

【问题讨论】:

标签: ruby


【解决方案1】:

您可以直接使用这些值。

def speak(name, age, address)
  puts "Hello #{name}!"
end

要访问您可以使用local_variables 的名称,但我不建议这样做。

def speak(name, age, address)
  p local_variables # => [:name, :age, :address]
end

但您很可能会想要使用哈希:

def speak(hash)
   # use the keys/values of hash
end

现在你可以使用

speak({:name => "foo", :age => 42, :address => "123"})
# or
speak(:name => "foo", :age => 42, :address => "123")

【讨论】:

  • 我说的是参数的变量名。我知道这听起来可能有点愚蠢,因为我已经应该知道参数变量的名称。
  • 那么为什么不能只使用 Hash 作为方法的参数呢?然后您将能够收集传递的名称-值对。为什么不呢?
  • 我知道使用哈希是最简单的方法,但我只是想知道是否可以在不使用哈希作为方法参数的情况下获取参数的变量名。
  • @denniss:再次查看已编辑的答案 :)
【解决方案2】:

您可以使用local_variables,但有更好的方法:

def speak(name, age, address)
  p self.method(__method__).parameters #=> [[:req, :name], 
                                            [:req, :age], 
                                            [:req, :address]]
end

当你使用local_variables时,你应该在方法的开头使用它:

def speak(name, age, address)
  foo = 1
  p local_variables #=> [:name, :age, :address, :foo]
end

【讨论】:

    【解决方案3】:

    找到答案了!

    def speak (name, age, address)
     puts local_variables
    end
    

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 2018-11-25
      • 2010-09-18
      • 2010-09-17
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2011-10-09
      相关资源
      最近更新 更多