Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14124

Modify elements of an array iterated with .each

I'm using an .each loop to iterate over an array. I want to change elements in this array, so I tried something like this:

ex = ["el01", "el02", "el03", "el04"]
ex.each do |el|
    if (el == "el02")
        el = "changed"
    end
end
puts ex

but it seems don't works! It puts me :

el01
el02
el03
el04

I want to know what I did wrong! or if it can't be done this way, how to do it.

Upvotes: 0

Views: 1385

Answers (3)

Marten
Marten

Reputation: 1356

The ruby way is to use the #each method of lists. And several other classes have #each, too, like Ranges. Therefore you will almost never see a for loop in ruby.

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 97004

You should use each:

ex = ["el01", "el02", "el03", "el04"]
ex.each do |str|
  # do with str, e.g., printing each element:
  puts str
end

Using for in Ruby is not recommended, as it simply calls each and it does not introduce a new scope.

However, if your intent is to change each element in the array, you should use map:

ex = ["el01", "el02", "el03", "el04"]
ex.map do |str|
  str.upcase
end
#=> ["EL01", "EL02", "EL03", "EL04"]

Upvotes: 2

vacawama
vacawama

Reputation: 154711

You can do that like this:

for item in ex
    #do something with the item here
    puts item
end

A more Ruby idiomatic way to do it is:

ex.each do |item|
    #do something with the item here
    puts item
end

Or, you can do it in one line:

ex.each {|item| puts item}

Upvotes: 1

Related Questions