Ruby - 从另一个方法中的循环调用方法

问题描述 投票:0回答:2

这是问题......

我有一个方法,我正在调用剥离字符并将字符串转换为浮点数。

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

到目前为止,它提出了错误,声明该类型不是浮点数,告诉我每个循环都没有转换值。

救命。

谢谢!!!

ruby methods each iteration
2个回答
1
投票

经过仔细检查,这里有两件事情出错。

  1. 将方法作为迭代函数传递的语法是错误的。 arrayoftotals.each do |convert_to_float| end 可以看作是一个空块,其中局部变量称为convert_to_float。您正在寻找的语法是: arrayoftotals.each (&method (:convert_to_float)) 这将传递一个Proc对象,引用convert_to_float方法作为块。
  2. 您没有更新arrayoftotals中的值。因此,即使调用convert_to_float,它也不会做任何事情。 要么将gsub更改为gsub!破坏性消毒你的琴弦,或使用地图!而不是每个替换数组中的每个元素与调用它的函数的结果。地图!是一个更好的选择,因为这意味着您不必调整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

2
投票

听起来像你在寻找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]

© www.soinside.com 2019 - 2024. All rights reserved.