mah*_*ich 6 ruby arrays string
如何将String:转换为s = '23534'数组:a = [2,3,5,3,4]
有没有办法迭代ruby中的chars并转换它们中的每一个,to_i甚至将字符串表示为Java中的char数组,然后转换所有字符to_i
正如你所看到的,我,在字符串中没有这样的分隔符,我在SO上找到的所有其他答案都包含一个分隔字符.
Nob*_*ita 16
一个简单的衬垫将是:
s.each_char.map(&:to_i)
#=> [2, 3, 5, 3, 4]
Run Code Online (Sandbox Code Playgroud)
如果你希望它是错误显式的,如果字符串不包含整数,你可以这样做:
s.each_char.map { |c| Integer(c) }
Run Code Online (Sandbox Code Playgroud)
ArgumentError: invalid value for Integer():如果你的字符串包含除整数之外的其他内容,则会引发一个.否则.to_i你会看到字符为零.
简短而简单:
"23534".split('').map(&:to_i)
Run Code Online (Sandbox Code Playgroud)
解释:
"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 }
Run Code Online (Sandbox Code Playgroud)