有没有办法在 Ruby 中访问方法参数? [英] Is there a way to access method arguments in Ruby?

查看:50
本文介绍了有没有办法在 Ruby 中访问方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 和 ROR 的新手并且每天都喜欢它,所以这是我的问题,因为我不知道如何用谷歌搜索它(我已经尝试过:))

New to Ruby and ROR and loving it each day, so here is my question since I have not idea how to google it (and I have tried :) )

我们有方法

def foo(first_name, last_name, age, sex, is_plumber)
    # some code
    # error happens here
    logger.error "Method has failed, here are all method arguments #{SOMETHING}"    
end

所以我正在寻找将所有参数传递给方法的方法,而不列出每个参数.由于这是 Ruby,我认为有一种方法:) 如果是 Java,我会列出它们:)

So what I am looking for way to get all arguments passed to method, without listing each one. Since this is Ruby I assume there is a way :) if it was java I would just list them :)

输出将是:

Method has failed, here are all method arguments {"Mario", "Super", 40, true, true}

推荐答案

在 Ruby 1.9.2 及更高版本中,您可以对方法使用 parameters 方法来获取该方法的参数列表.这将返回一个对列表,指示参数的名称以及是否需要它.

In Ruby 1.9.2 and later you can use the parameters method on a method to get the list of parameters for that method. This will return a list of pairs indicating the name of the parameter and whether it is required.

例如

如果你这样做

def foo(x, y)
end

然后

method(:foo).parameters # => [[:req, :x], [:req, :y]]

您可以使用特殊变量 __method__ 来获取当前方法的名称.所以在一个方法中,可以通过

You can use the special variable __method__ to get the name of the current method. So within a method the names of its parameters can be obtained via

args = method(__method__).parameters.map { |arg| arg[1].to_s }

然后您可以使用

logger.error "Method failed with " + args.map { |arg| "#{arg} = #{eval arg}" }.join(', ')

<小时>

注意:由于这个答案最初是写的,在当前版本的 Ruby eval 中不能再用符号调用.为了解决这个问题,在构建参数名称列表时添加了显式 to_s,即 parameters.map { |arg|arg[1].to_s }


Note: since this answer was originally written, in current versions of Ruby eval can no longer be called with a symbol. To address this, an explicit to_s has been added when building the list of parameter names i.e. parameters.map { |arg| arg[1].to_s }

这篇关于有没有办法在 Ruby 中访问方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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