0

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.

3
  • 1
    if you googled this up you would have got thousand of answers, you clearly don't understand the purpose of stackoverflow, read the faq first please Commented Oct 6, 2012 at 23:30
  • @peter I'm now more clear about this question, and Andrew answers me with .map that I didn't know before, can you please vote-it up ? I can no longer ask questions in stackoverflow because of this question. Commented Jul 22, 2013 at 14:59
  • i didn't vote you down you know, but i'll give you a +,in the future please search first, try thing out second and only then ask a question after having checked if it's not allready asked Commented Jul 22, 2013 at 21:10

3 Answers 3

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

1

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}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.