如何在Ruby中将人类可读的数字转换为计算机可读的数字? [英] How can I convert a human-readable number to a computer-readable number in Ruby?

查看:55
本文介绍了如何在Ruby中将人类可读的数字转换为计算机可读的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby中使用的数组中包含一系列易于理解的数字(例如2.5B,1.27M,600,000,其中 B代表十亿, M代表百万)。我正在尝试将数组的所有元素转换为相同的格式。

I'm working in Ruby with an array that contains a series of numbers in human-readable format (e.g., 2.5B, 1.27M, 600,000, where "B" stands for billion, "M" stands for million). I'm trying to convert all elements of the array to the same format.

这是我编写的代码:

array.each do |elem|
    if elem.include? 'B'
        elem.slice! "B"
        elem = elem.to_f
        elem = (elem * 1000000000)
    else if elem.include? 'M'
        elem.slice! "M"
        elem = elem.to_f
        elem = (elem * 1000000)
    end
end

当我使用 puts(array)检查数组的元素时,数字以 B和切掉了 M,但似乎未应用乘法转换(例如,现在读取的数字为2.5、1.27、600,000,而不是2500000000、1270000、600,000)。

When I inspect the elements of the array using puts(array), however, the numbers appear with the "B" and "M" sliced off but the multiplication conversion does not appear to have been applied (e.g., the numbers now read 2.5, 1.27, 600,000, instead of 2500000000, 1270000, 600,000).

我在做什么错了?

推荐答案

尝试一下:

array.map do |elem|
    elem = elem.gsub('$','')
    if elem.include? 'B'
        elem.to_f * 1000000000
    elsif elem.include? 'M'
        elem.to_f * 1000000
    else
        elem.to_f
    end
end

这将使用 map 而不是每个 返回一个新数组。您的尝试将分配数组元素的副本,从而将原始数组保留在原位置( slice!除外,该数组将在适当位置进行修改)。您可以首先省去切片,因为 to_f 只会忽略任何非数字字符。

This uses map instead of each to return a new array. Your attempt assigns copies of the array elements, leaving the original array in place (except for the slice!, which modifies in place). You can dispense with the slicing in the first place, since to_f will simply ignore any non-numeric characters.

编辑:

如果您有前导字符,例如 $ 2.5B ,请参见问题标题(但不包括示例) ),则需要显式删除这些内容。但是您的示例代码也无法处理这些问题,因此我认为这不是问题。

If you have leading characters such as $2.5B, as your question title indicates (but not your example), you'll need to strip those explicitly. But your sample code doesn't handle those either, so I assume that's not an issue.

这篇关于如何在Ruby中将人类可读的数字转换为计算机可读的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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