0

I know that I can use

my_array = [1,2,3,4,5]
my_array.each {|element| puts element}

to do something with each element of an array but what if I need to do several things with each element? It starts complaining when I try to put multiple statements in the block. What I am really looking for is something more like this:

my_array = [1,2,3,4,5]
my_array.each |element| do
  #operation one involving the element
  #operation two involving the element
  ...
end

Is there any good way to achieve this effect?

2
  • 2
    Who is complaining? You can do multiple operations in the block. What is the error you're seeing? Do you have a more concrete code example that shows what's generating the error? Commented Mar 6, 2014 at 2:51
  • 1
    the second chunk should work pretty much as is if you move 'do' to immediately after 'each' Commented Mar 6, 2014 at 2:54

2 Answers 2

4

You can put as many statements as you like inside a block, but you need to get the do/end syntax right.

The order is do |elemenet|, not |element| do. The do/end keywords replace the {}.

my_array.each do |element|
  puts "element is #{element}"
  element += 1
  puts "Now element is #{element}"
  # etc...
end
Sign up to request clarification or add additional context in comments.

Comments

1

If you really want to cram it into a one liner you can use semicolons.

x = [1,2,3,4,5]
x.map{|y| y*=2; y-=5; y}

This gives you: => [-3, -1, 1, 3, 5]

It gets pretty ugly pretty fast though, so use multiliners unless there's a really good reason you want it on one line.

1 Comment

I think there are perfectly valid uses for this

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.