2016-04-17 60 views
4

如何轉換爲字符串:s = '23534'到數組作爲這樣的:a = [2,3,5,3,4]字符串轉換爲int數組紅寶石

有沒有辦法來迭代在紅寶石字符並將其轉換的每個to_i甚至有字符串表示的字符數組在Java中,然後將所有字符to_i

正如你所看到的,我沒有一個分隔符作爲字符串這樣,,我發現所有其他答案SO包括一個界定字符。

回答

9

下一個簡單襯墊w ^烏爾德是:

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

我喜歡它是錯誤顯式的想法 – mahatmanich

2

您可以使用String#each_char

array = [] 
s.each_char {|c| array << c.to_i } 
array 
#=> [2, 3, 5, 3, 4] 

或者只是s.each_char.map(&:to_i)

+0

ahhhh each_char救援......正是我所忽略的字符串API ... – mahatmanich

3

短而簡單:

"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 } 
1

在Ruby 1.9.3,你可以做以下的一串數字轉換爲數字的數組:分裂的逗號後

沒有空格(「」),你會得到這樣的: 「1 ,2,3「.split(',')#=> [」1「,」2「,」3「]

在split(',')逗號之後留有空格: 「1,2,3」.split(',')#=> [「1,2,3」]

分隔符(',')後面沒有空格,表示爲: 「1 ,2,3「.split(',')。map(&:to_i)#=> [1,2,3]

隨着分裂的逗號( ' ')之後的空間中收到此: 「1,2,3」 .split(',').MAP(&:to_i)#=> [1]