如何将字符串:s = '23534'
转换为数组:a = [2,3,5,3,4]
有没有办法迭代ruby中的字符并转换每个字符to_i
甚至将字符串表示为Java数组中的char数组,然后转换所有字符to_i
< / p>
正如您所看到的,我在字符串中没有,
这样的分隔符,我在SO上找到的所有其他答案都包含一个分隔字符。
答案 0 :(得分:14)
简单的一个班轮将是:
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
,您会看到字符为零。
答案 1 :(得分:4)
简短而简单:
"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 }
答案 2 :(得分:3)
您可以使用String#each_char
:
array = []
s.each_char {|c| array << c.to_i }
array
#=> [2, 3, 5, 3, 4]
或只是s.each_char.map(&:to_i)
答案 3 :(得分:2)
在Ruby 1.9.3中,您可以执行以下操作将数字字符串转换为数字数组:
在分割逗号之后没有空格(&#39;,&#39;)你得到这个: &#34; 1,2,3&#34; .split(&#39;,&#39;)#=&gt; [&#34; 1&#34;&#34; 2&#34;&#34; 3&#34;]
在分割逗号后面加一个空格(&#39;,&#39;)你得到这个: &#34; 1,2,3&#34; .split(&#39;,&#39;)#=&gt; [&#34; 1,2,3&#34;]
在分割逗号之后没有空格(&#39;,&#39;)你得到这个: &#34; 1,2,3&#34; .split(&#39;,&#39;)。map(&amp;:to_i)#=&gt; [1,2,3]
在分割逗号后面加一个空格(&#39;,&#39;)你得到这个: &#34; 1,2,3&#34; .split(&#39;,&#39;)。map(&amp;:to_i)#=&gt; [1]
答案 4 :(得分:0)
有多种方法,我们可以做到这一点。
'12345'.chars.map(&:to_i)
'12345'.split("").map(&:to_i)
'12345'.each_char.map(&:to_i)
'12345'.scan(/\w/).map(&:to_i)
我最喜欢第三名。更具表现力和简单性。