Search code examples
ruby-on-railsruby

What is the most concise way to initialize a Ruby array with at least one default value?


In Ruby, I have an object that has an array. I want to iterate over the values in the array, but I need there to be at least one item in the array. I know I could do something like this:

if object.initial_array.empty?
  object.initial_array << "foo"
end
object.initial_array.each do ...

But I'd like to be able to do this in one line. What is the most concise way of enumerating an array and specify a default value if empty?


Solution

  • Just make your initial_array method have the default, like:

      attr_accessor :initial_array
    
      def initial_array
        @initial_array.presence || @initial_array = %w[foo]
      end