简体   繁体   中英

How to use each_with_index in Ruby and to convert to numbered list?

I am wondering how do I convert an array to a numbered list using the each_with_index .

def roll_call_dwarves(dwarves)# code an argument here
  roll_call_dwarves = dwarves
  dwarves.each_with_index {|x, y|}
  puts dwarves
end

Not sure exactly what you want, but if you just want to render the list with numbers, you could try something like:

def roll_call_dwarves(dwarves)
  dwarves.map.with_index do |dwarf, i|
    "#{i + 1}. #{dwarf}"
  end.join("\n")
end

dwarves = %w{Doc Dopey Bashful Grumpy}
puts roll_call_dwarves(dwarves)

This gives you:

1. Doc
2. Dopey
3. Bashful
4. Grumpy

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