2011-04-24 47 views
2

我有要找到整數(Fixnum對象)值在紅寶石陣列

  • 純整數(12)陣列[1, 2, "3", "4", "1a", "abc", "a"]
  • 串格式化整數("1""2"),
  • 串("a","b")和
  • 混合字符串編號("1a","2s")。

從此,我需要拿起唯一的整數(包括格式化字符串)12"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_ito_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 } 

現在,我得到整數和字符串的數組。有沒有簡單的方法來做到這一點?

+0

-1。你寫出你的數組包含字符串格式的整數「1」,「2」,但它們不在你的數組中。此外,未找到字符串「b」和混合字符串數字「2s」。 – sawa 2011-04-24 17:08:40

+0

是否需要將其作爲整數或原始類型返回。我需要獲得'[1,2,3,4]'還是'[1,2,'3','4']'? – fl00r 2011-04-24 17:34:45

+0

@sawa,它是一個錯字sawa ...我打算輸入「3」,「4」。說字符串格式化數字有什麼不同。我想傳達一個例子... – RameshVel 2011-04-25 07:05:35

回答

5

類似的解決方案,通過提供@maerics,但有點渺茫:

arr.map {|x| Integer(x) rescue nil }.compact 
+2

我想發佈幾乎相同,但使用'select'像這樣:'>> a.select {| i | Integer(i)rescue false}#=> [1,2,「3」,「4」]'。無論如何,因爲解決方案非常相似,我會讓你有這個。 :-) – 2011-04-24 16:11:51

+0

我會說這個成語是比pythonist更多的rubyist「請求原諒不允許」。然而,在Ruby中,爲了挽救一個異常可能在性能方面很昂貴,請參閱這個基準:http://technicaldebt.com/the-cost-of-using-rubys-rescue-as-logic/ – vruizext 2015-09-26 13:55:32

3
class Array 
    def to_i 
    self.map {|x| begin; Integer(x); rescue; nil; end}.compact 
    end 
end 

arr = [1, 2, "3", "4", "1a", "abc", "a"] 
arr.to_i # => [1, 2, 3, 4] 
+0

多數民衆贊成在整齊.. :) – RameshVel 2011-04-24 08:29:49

2

是這樣的:

a = [1,2,"3","4","1a","abc","a"] 



irb(main):005:0> a.find_all { |e| e.to_s =~ /^\d+$/ }.map(&:to_i) 
=> [1, 2, 3, 4] 
+0

我會把'to_i'在'find_all'塊內。這阻止了雙重迭代。 – Swanand 2011-04-24 10:26:13

1

嘿,感謝我的覺醒紅寶石。這是我走在這個問題:

arr=[1,2,"3","4","1a","abc","a"] 
arr.map {|i| i.to_s}.select {|s| s =~ /^[0-9]+$/}.map {|i| i.to_i} 
//=> [1, 2, 3, 4] 
1

我注意到大部分的答案至今改變了「3」值和「4」爲實際整數。

>> array=[1, 2, "3", "4", "1a", "abc", "a", "a13344a" , 10001, 3321] 
=> [1, 2, "3", "4", "1a", "abc", "a", "a13344a", 10001, 3321] 
>> array.reject{|x| x.to_s[/[^0-9]/] } 
=> [1, 2, "3", "4", 10001, 3321] 

@OP,我沒有測試過我的解決方案詳盡,但到目前爲止,似乎工作(當然其根據所提供的樣品進行),所以請徹底測試自己。

1

這個怎麼樣?

[1,2,"3","4","1a","abc","a"].select{|x| x.to_i.to_s == x.to_s} 
# => [1, 2, "3", "4"] 
0

看起來很簡單

arr.select{ |b| b.to_s =~ /\d+$/ } 
# or 
arr.select{ |b| b.to_s[/\d+$/] } 
#=> [1, 2, "3", "4"]