Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回一个参数';s名称而不是它的值-Ruby_Ruby - Fatal编程技术网

返回一个参数';s名称而不是它的值-Ruby

返回一个参数';s名称而不是它的值-Ruby,ruby,Ruby,我需要打印.max函数的结果,但显示其参数的名称,而不是.max方法使用的目标值(数字) def who_is_bigger(a,b,c) "#{[a,b,c].max} is bigger" end 预期结果: expect(who_is_bigger(84, 42, 21)).to eq("a is bigger") expect(who_is_bigger(42, 84, 21)).to eq("b is bigger") expect(who_is_bigger(42, 21, 8

我需要打印.max函数的结果,但显示其参数的名称,而不是
.max
方法使用的目标值(数字)

def who_is_bigger(a,b,c)
  "#{[a,b,c].max} is bigger"
end
预期结果:

expect(who_is_bigger(84, 42, 21)).to eq("a is bigger")
expect(who_is_bigger(42, 84, 21)).to eq("b is bigger")
expect(who_is_bigger(42, 21, 84)).to eq("c is bigger")

据我所知,从参数的值中获取参数的名称并不是一种简单易懂的方法。(请参见答案的底部,了解这样做的一种方法。)

相反,我会这样做,我认为这样做很好,可读性强:

def who_is_bigger(a,b,c)
  values = {a: a, b: b, c: c}
  largest_key, _ = values.max_by { |key, value| value }
  "#{largest_key} is bigger"
end
这项工作如下:

  • 从参数中构建散列,并将其存储在
    值中。例如,这个散列可以是
    {a:84,b:42,c:21}
  • 使用方法查找该哈希中的最大值。这将在
    最大的\u对中存储2个项目的数组,例如
    [:a,84]
    。请注意我们想要的密钥是如何作为第一项的,因此我们使用解构来提取该对中的第一项,并将其存储在
    最大\u密钥中

  • 构造字符串并从方法返回它


  • 如果希望以动态访问和迭代参数名称和值的方式执行此操作,可以使用以下方法:

    def who_is_bigger(a,b,c)
      params = method(__method__).parameters
      values = params.map { |_, name| [name, binding.local_variable_get(name)] }.to_h
      largest_key, _ = values.max_by { |key, value| value }
      "#{largest_key} is bigger"
    end
    

    不过,在我看来,与其他解决方案相比,这感觉有点粗糙,更难阅读。

    下面是使用Ruby并从Ruby执行此操作的另一种方法:

    def who_is_bigger(a, b, c)
      biggest = binding.local_variables.max_by do |v|
                  binding.local_variable_get(v) || -Float::INFINITY
                end
      "#{biggest} is biggest"
    end
    
    who_is_bigger(10, 21, 30)
    => "c is biggest"
    
    who_is_bigger(40, 31, 30)
    => "a is biggest"
    

    你可以使用
    maximum\u key,maximum\u value=values.max\u by{…}
    将键和值分配给不同的变量。啊,是的,那看起来更干净了!您的第一句话表明有一种方法可以从值中获取名称,尽管这很难理解或需要努力。如果你知道这是真的,你至少应该概述一下程序;如果你不知道这是真的,你不应该建议它。还有,在“没有真正的……”中,“真正的”是什么意思?准确点@CarySwoveland足够公平-添加到答案的底部。