2011-04-13 84 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 }