2011-04-13 97 views
33

如何得到以下情況:我想更改.each循環中管道字符之間引用的數組元素的值。更改.each循環中引用的數組元素的值?

這裏是我想要做一個例子,但當前未工作:

x = %w(hello there world) 
x.each { |element| 
    if(element == "hello") { 
     element = "hi" # change "hello" to "hi" 
    } 
} 
puts x # output: [hi there world] 

很難查找東西,所以一般。

+1

有一系列名爲[Enumerating enumerable]的博客文章(http://www.globalnerdy.com/tag/enumerating-enumerable/),您可能會覺得有用。 – 2011-04-13 22:30:05

回答

25

each方法永遠不會更改它的工作對象。

您應該使用map!方法代替:

x = %w(hello there world) 
x.map! { |element| 
    if(element == "hello") 
     "hi" # change "hello" to "hi" 
    else 
     element 
    end 
} 
puts x # output: [hi there world] 
+0

你爲什麼把'hi「分配給'element'? 'element'是一個塊本地變量,它立即超出範圍。這根本沒有意義。 – 2011-04-13 10:34:11

+1

你完全正確。複製並粘貼並忘記修復。 – Yossi 2011-04-13 10:55:51

33

你可以得到你想要使用collect!map!修改就地數組結果:

x = %w(hello there world) 
x.collect! { |element| 
    (element == "hello") ? "hi" : element 
} 
puts x 

在每次迭代中,元素被塊返回的值替換到數組中。

8

地圖可能是最好的方法,但您也可以更改字符串。

> a = "hello" 
> puts a 
=> hello 

> a.replace("hi") 
> puts a 
=> hi 

更改字符串的內部值。例如,你的代碼可能會變成:

x = %w(hello there world) 
x.each { |e| if (e == "hello"); e.replace("hi") end; } 

但這是好得多:

x = %w(hello there world) 
x.map! { |e| e == "hello" ? "hi" : e } 
+0

+1,做事很死板。雖然沒有具體回答這個問題,但您也可以通過索引來替換,即[0] .replace('HI')。那就是我一直在尋找的東西,你的回答讓我感覺到了。乾杯! – SRack 2015-12-07 12:17:24

2
x = %w(hello there world) 
x[index] = "hi" if index = x.index("hello") 
x[index] = "hi" if index 

x = %w(hello there world) 
index = x.index("hello") and x[index] = "hi" 

但一個通知:它只會取代第一個匹配。否則,使用map!作爲@SirDarlus suggested

您也可以使用each_with_index

x.each_with_index do |element, index| 
    x[index] = "hi" if element == "hello" # or x[index].replace("hi") if element == "hello" 
end 

但我還是喜歡用map! :)

+0

我喜歡使用'each_with_index'的最後一個,因爲它不會做額外的事情。 – sawa 2011-04-13 10:22:27

1

這是一種具有較少的代碼行:

x = %w(hello there world) 
    x = x.join(",").gsub("hello","hi").split(",") 
    puts x 
1

簡單來說:

x = %w(hello there world).map! { |e| e == "hello" ? "hi" : e }