- 純整數(
1
,2
)陣列[1, 2, "3", "4", "1a", "abc", "a"]
, - 串格式化整數(
"1"
,"2"
), - 串(
"a"
,"b"
)和 - 混合字符串編號(
"1a"
,"2s"
)。
從此,我需要拿起唯一的整數(包括格式化字符串)1
2
"3"
"4"
,,,。
首先,我試着用to_i
:
arr = [1, 2, "3", "4", "1a", "abc", "a"]
arr.map {|x| x.to_i}
# => [1, 2, 3, 4, 1, 0, 0]
但這個轉換"1a"
到1
,我不指望。
然後我試圖Integer(item)
:
arr.map {|x| Integer(x) } # and it turned out to be
# => ArgumentError: invalid value for Integer(): "1a"
現在我離開這裏直接轉換選項。最後,我決定這樣做,它將轉換價值to_i
和to_s
。所以"1" == "1".to_i.to_s
是一個整數,但不"1a" == "1a".to_i.to_s
和"a" == "a".to_i.to_s
arr = arr.map do |x|
if (x == x.to_i.to_s)
x.to_i
else
x
end
end
和
ids, names= arr.partition { |item| item.kind_of? Fixnum }
現在,我得到整數和字符串的數組。有沒有簡單的方法來做到這一點?
-1。你寫出你的數組包含字符串格式的整數「1」,「2」,但它們不在你的數組中。此外,未找到字符串「b」和混合字符串數字「2s」。 – sawa 2011-04-24 17:08:40
是否需要將其作爲整數或原始類型返回。我需要獲得'[1,2,3,4]'還是'[1,2,'3','4']'? – fl00r 2011-04-24 17:34:45
@sawa,它是一個錯字sawa ...我打算輸入「3」,「4」。說字符串格式化數字有什麼不同。我想傳達一個例子... – RameshVel 2011-04-25 07:05:35