简体   繁体   中英

ruby/rails how to insert column into multidimensional array

I have an array arr = [[1,2],[3,4]] and a column col = [5,6]

Is there an easy way to get an output of [[1,2,5],[3,4,6]] without looping? Thanks

Yes, using Array#transpose as follows:

arr = [[1,2],[3,4]]
col = [5,6]
pp (arr.transpose << col).transpose # => [[1, 2, 5], [3, 4, 6]]

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