更改.each循环中引用的数组元素的值?

时间:2011-04-13 08:57:19

标签: arrays ruby

如何实现以下目标:我想更改.each循环中管道字符之间引用的数组元素的值。

以下是我想要做的一个示例,但目前无法使用:

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

很难找到如此普遍的东西。

7 个答案:

答案 0 :(得分:36)

您可以使用collect!map!来获取所需的结果,以便就地修改数组:

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

在每次迭代时,元素将被块返回的值替换为数组。

答案 1 :(得分:26)

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]

答案 2 :(得分:9)

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

> 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 }

答案 3 :(得分:3)

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!:)

答案 4 :(得分:1)

这种方法的代码行数较少:

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

答案 5 :(得分:1)

简单地说:

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

答案 6 :(得分:0)

很简单,你也可以这样做 -

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