Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
是否有等效于 fixnum 的 String chars 方法?我试图将一个整数值按值分隔到一个数组中,例如 1234 -> [1, 2, 3, 4] 然后对各个值执行操作。
还是先转换为字符串,执行操作(例如 x 2)然后以整数形式连接更好?如下所示:
def method_name num num.to_s.chars.map{|x| x.to_i*2}.join.to_i end
没有什么可以将数字拆分为单个数字,因为这通常与数字有关。你也可以用数学的方式来做,但考虑到要求(到目前为止),我认为这样做没有明显的优势。
我可能更喜欢拆分转换和乘法,例如,
n.to_s.chars.map(&:to_i).map { |n| n * 2 }.join.to_i
它的用途更广,如果乘数发生变化,则很容易更改(此处未显示,但有一些方法)。