【发布时间】:2026-02-21 23:20:03
【问题描述】:
如何将字符串:s = '23534' 转换为数组:a = [2,3,5,3,4]
有没有办法遍历 ruby 中的字符并转换它们中的每一个 to_i 或者甚至像在 Java 中那样将字符串表示为 char 数组,然后转换所有字符 to_i
如您所见,我在字符串中没有 , 这样的分隔符,我在 SO 上找到的所有其他答案都包含一个分隔符。
【问题讨论】:
如何将字符串:s = '23534' 转换为数组:a = [2,3,5,3,4]
有没有办法遍历 ruby 中的字符并转换它们中的每一个 to_i 或者甚至像在 Java 中那样将字符串表示为 char 数组,然后转换所有字符 to_i
如您所见,我在字符串中没有 , 这样的分隔符,我在 SO 上找到的所有其他答案都包含一个分隔符。
【问题讨论】:
一个简单的衬线是:
s.each_char.map(&:to_i)
#=> [2, 3, 5, 3, 4]
如果字符串不只包含整数,如果你希望它是错误显式的,你可以这样做:
s.each_char.map { |c| Integer(c) }
如果您的字符串包含除整数以外的其他内容,这将引发ArgumentError: invalid value for Integer():。否则对于.to_i,您会看到字符为零。
【讨论】:
简短:
"23534".split('').map(&:to_i)
解释:
"23534".split('') # Returns an array with each character as a single element.
"23534".split('').map(&:to_i) # shortcut notation instead of writing down a full block, this is equivalent to the next line
"23534".split('').map{|item| item.to_i }
【讨论】:
你可以使用String#each_char:
array = []
s.each_char {|c| array << c.to_i }
array
#=> [2, 3, 5, 3, 4]
或者只是s.each_char.map(&:to_i)
【讨论】:
在 Ruby 1.9.3 中,您可以执行以下操作将数字字符串转换为数字数组:
split(',') 的逗号后没有空格,你会得到: "1,2,3".split(',') # => ["1","2","3"]
在 split(', ') 的逗号后有一个空格,您会得到: "1,2,3".split(', ') # => ["1,2,3"]
split(',') 的逗号后没有空格,你会得到: "1,2,3".split(',').map(&:to_i) # => [1,2,3]
在 split(', ') 的逗号后有一个空格,您会得到: "1,2,3".split(', ').map(&:to_i) # => [1]
【讨论】:
有多种方法,我们可以做到这一点。
'12345'.chars.map(&:to_i)
'12345'.split("").map(&:to_i)
'12345'.each_char.map(&:to_i)
'12345'.scan(/\w/).map(&:to_i)
我最喜欢第三个。更具表现力和简单性。
【讨论】:
'23534'.to_i.digits.reverse