Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.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
Ruby on rails 如何在RubyonRails中将三个映射函数合并为一个?_Ruby On Rails_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 如何在RubyonRails中将三个映射函数合并为一个?

Ruby on rails 如何在RubyonRails中将三个映射函数合并为一个?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我试图在一个函数中重写这三个函数: def self.net_amount_by_year(year) year(year).map(&:net_amount).sum end def self.taxable_amount_by_year(year) year(year).map(&:taxable_amount).sum end def self.gross_amount_by_year(year) year(year).map(&:gross_amo

我试图在一个函数中重写这三个函数:

def self.net_amount_by_year(year)
  year(year).map(&:net_amount).sum
end

def self.taxable_amount_by_year(year)
  year(year).map(&:taxable_amount).sum
end

def self.gross_amount_by_year(year)
  year(year).map(&:gross_amount).sum
end
有人能帮忙吗

到目前为止,我得到的是:

def self.amount_by_year(type_of_amount, year)
  year(year).map(&type_of_amount.to_sym).sum
end
当然,金额的
&type\u位不起作用。我想知道如何做到这一点

谢谢你的帮助

顺便说一下,我甚至不知道
&
是做什么用的。有人能解释一下吗

这应该有效:

def self.amount_by_year(type_of_amount, year)
  year(year).map{|y| y.send(type_of_amount)}.sum
end
事实上,您应该能够做到这一点:

def self.amount_by_year(type_of_amount, year)
  year(year).sum{|y| y.send(type_of_amount)}
end
参考文献:


如果给代码一个符号(
to_sym
是多余的),那么代码应该按原样工作

要传递的金额的类型应为
:净金额
:应纳税金额
,或
:总金额

如果要压缩参数,甚至可以执行以下操作:

def self.amount_by_year(type, year)
  year(year).map(&:"#{type}_amount").sum
end
并传递到
类型
:净
:应税
,或
:总额

事实上,你可以做到:

def self.amount_by_year(type, year)
  year(year).sum(&:"#{type}_amount")
end

顺便说一句,&in映射是引用对象上的属性或方法的简写(代替使用块,正如我在上面的回答中所做的)。根据使用情况,为安全起见,您可以添加一项检查,以确保
类型的金额与您的三种方法之一匹配。您不希望有人按年份调用
amount\u(:delete,2013)
Kyle绝对正确,您应该以某种方式将传递的属性/方法列入白名单。虽然我的回答满足了您的问题,但我会谨慎地以这种方式设计应用程序。这也是非常好的。非常感谢。我仍然想知道这里最好的是什么,
.map(..).sum
,或者像Carlos建议的那样使用一个块。你可以将它们组合起来,使其更短。见我的补充。
def self.amount_by_year(type, year)
  year(year).sum(&:"#{type}_amount")
end