2011-03-20 24 views
0

我想映射數組的元素,使得數組的所有元素 都是浮點數,除了第一個元素是 是一個字符串。基於位置映射數組的不同元素

任何人都知道我該怎麼做?

試過,但不起作用:

arr = arr.map { |e| e.to_i if e != arr.first } 
+2

爲什麼不編輯你的問題,並提供一些樣本數據,以及所需輸出的例子呢? – 2011-03-20 03:01:41

回答

2

另一種解決方案是

[array.first] + array.drop(1).map &:to_f 

這清楚地表明,要在第一元件從其餘部分分離,並且想要的元素的其餘部分是Float類型。其他選項包括

array.map { |element, index| index == 0 ? element : element.to_f } 
array.map { |element| element == array.first ? element : element.to_f } 
+0

我認爲你的意思是:[array.first] + ....這確實是最好的解決方案,不檢查循環內部。 – tokland 2011-03-20 09:25:46

1

你可以用很短的三元表達式的位置:

a.map { |e| (e == a.first) ? e : e.to_f } 
1

另一種選擇(如果你不希望使用三元經營者)被要做到以下幾點:

arr = arr.map { |e| (e == arr.first) && e || e.to_f} 

這個替代方案是討論here。此方法的一個限制是數組中的第一個元素不能爲零(或者其他值可以在布爾評估中評估爲false),因爲如果是這樣,它將計算到||表達式並返回e.to_f而不僅僅是即

1

Ruby 1.9 only?

arr = arr.map.with_index { |e, i| i.zero? ? e.to_s : e.to_f } 
1

您可以詢問對象本身是否是數字。

"column heading".respond_to?(:to_int) # => false 
3.1415926.respond_to?(:to_int) # => true 

new_arr = arr.map do |string_or_float| 
    if string_or_float.respond_to?(:to_int) 
    string_or_float.to_int # Change from a float into an integer 
    else 
    string_or_float # Leave the string as-is 
    end 
end 

respond_to?(:to_int)的意思是 「我能叫to_int你嗎?」

to_int是一種只能輕鬆轉換爲整數的對象應具有的方法。不像to_i,這是「我不是很像一個整數,但你可以嘗試將我轉換成一個整數」,to_int的意思是「我非常像一個整數 - 將我完全置信地轉換成一個整數!」

+0

啊,這是整潔:) – Flethuseo 2011-03-21 19:19:53