如何将字符串:s = '23534'
转换为以下数组:a = [2,3,5,3,4]
在 Ruby 中,是否有一种方法可以迭代字符串中的字符,并将每个字符转换为 to_i
或者将字符串表示为字符数组(就像 Java 中那样),然后将所有字符转换为 to_i
?
正如您所看到的,我没有像字符串中的其他答案一样包含分隔符 ,
。
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
,您将看到字符的值为零。
如果您的字符串包含的不是整数,则会引发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 }
'12345'.chars.map(&:to_i)
'12345'.split("").map(&:to_i)
'12345'.each_char.map(&:to_i)
'12345'.scan(/\w/).map(&: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)
'23534'.to_i.digits.reverse
- steenslag