DEV Community

Arrays in Ruby

Augusto Kato on August 19, 2023

Today I learned about arrays and their methods in Ruby. Creating Arrays Here are two basic arrays, created by an array literal: num_...
Collapse
 
birdie0 profile image
Birdie

Worth mention that Array.new also supports block:

Array.new(3) {|index| index * 2 } #=> [0, 2, 4]
Enter fullscreen mode Exit fullscreen mode

and have to be used if default value is hash/array/object/etc. otherwise they'll share same reference.

# ❌
arr = Array.new(3, {})
arr.first[:a] = 5
arr #=> [{:a=>5}, {:a=>5}, {:a=>5}]

# ✅
arr = Array.new(3) { {} }
arr.first[:a] = 5
arr #=> [{:a=>5}, {}, {}]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
harkato profile image
Augusto Kato

Thanks! I will update the article with this changes!

Collapse
 
cherryramatis profile image
Cherry Ramatis

Nice article!