简体   繁体   中英

How to get all diagonal from an array of words in Ruby?

I have an array in Ruby

words = ["horses", "follow", "useful", "offset"]

Reference:

h o r s e s
f o l l o w
u s e f u l
o f f s e t

I want to get a list of all its diagonals like this. Here is want I expect in result:

["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]

Would be helpful if anyone can help me a bit on this. Thanks

Try that:

words = ["horses", "follow", "useful", "offset"]

words.reverse.each_with_index.map{|s,i| " " * i + s }.inject(Array.new(words.size + words.last.size-1,"")) do |a,s| 
  s.chars.each_with_index do |c,i| 
    a[i] = c + a[i]
  end
  a
end.map(&:strip)
# => ["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]

At first words.reverse.each_with_index.map{|s,i| " " * i + s } words.reverse.each_with_index.map{|s,i| " " * i + s } builds array with whitespace offset:

offset
 useful
  follow
   horses

Inject creates array of empty strings and inside main block each string chars are prepended to proper array element

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