简体   繁体   中英

Ruby Do Multiple Things With Each Element of an Array

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM