这是问题......
我有一个方法,我正在调用剥离字符并将字符串转换为浮点数。
def convert_to_float(currency)
return currency.gsub(/regex/, "").to_f
end
我有另一种接收字符串值的方法。我想要做的是通过convert_to_float方法迭代那些接收到的字符串,而不是将gsub应用于每一行。这就是我所拥有的......这就是我这样做的方式吗?
def verify_amounts(total,subtotal,tax)
arrayoftotals = [total,subtotal,tax]
arrayoftotals.each do |convert_to_float|
end
ftotal = arrayoftotals[0]
raise "ftotal must be a Float" unless ftotal.kind_of? Float
end
到目前为止,它提出了错误,声明该类型不是浮点数,告诉我每个循环都没有转换值。
救命。
谢谢!!!
经过仔细检查,这里有两件事情出错。
arrayoftotals.each do |convert_to_float|
end
可以看作是一个空块,其中局部变量称为convert_to_float。您正在寻找的语法是:
arrayoftotals.each (&method (:convert_to_float))
这将传递一个Proc对象,引用convert_to_float方法作为块。把它们放在一起:
def convert_to_float(currency)
return currency.gsub(/regex/, "").to_f
end
def verify_amounts(total,subtotal,tax)
arrayoftotals = [total,subtotal,tax]
arrayoftotals.map! (&method (:convert_to_float)
ftotal = arrayoftotals[0]
raise "ftotal must be a Float" unless ftotal.kind_of? Float
end
听起来像你在寻找map
:
arrayoftotals = [total, subtotal, tax].map { |x| convert_to_float(x) }
或者,因为convert_to_float
是与verify_amounts
在同一类中的方法,所以你可以使用Object#method
method来编写它:
arrayoftotals = [total, subtotal, tax].map(&method(:convert_to_float))
例如,这个:
class Pancakes
def convert_to_float(currency)
currency.gsub(/[^\d.]/, '').to_f
end
def verify_amounts(total, subtotal, tax)
arrayoftotals = [total, subtotal, tax].map(&method(:convert_to_float))
puts arrayoftotals.inspect
end
end
Pancakes.new.verify_amounts('where1.0', '2.is0', '3.0house')
会在标准输出上给你[1.0, 2.0, 3.0]
。