45

Perl is pretty nice about default values:

: jmglov@laurana; perl -e '@foo; printf "%d\n", $foo[123]'
0
: jmglov@laurana; perl -e '%foo; printf "%d\n", $foo{bar}'
0

Ruby can do the same, at least for hashes:

>> foo = Hash.new(0)
=> {}
>> foo[:bar]
=> 0

But the same seemingly does not work for arrays:

>> foo = Array.new(0)
=> []
>> foo[123]
=> nil
>> foo[124] = 0
=> 0
>> foo[456] = 0
=> 0
>> foo[455,456]
=> [nil, 0]

Is it possible to supply a default value for arrays, so when they are auto-extended, they're filled with 0 instead of nil?

Of course I can work around this, but at a cost to expressiveness:

>> foo[457,458] = 890, 321
=> [890, 321]
>> foo[456] += 789
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
>> foo.inject(0) {|sum, i| sum += (i || 0) }
=> 1211
>> foo.inject(:+)
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

Update 1: One of my colleagues pointed out that I can use #compact to solve the #inject issue, and #to_i to solve the standard element-at-index issue:

>> foo.include? nil
=> true
>> foo.compact.inject(:+)
=> 1211
>> foo[456,457]
=> [0, 890, 321]
>> foo[455..457]
=> [nil, 0, 890]
>> foo[455..457].map(&:to_i)
=> [0, 0, 890]

Update 2: Thanks to Andrew Grimm for a solution to the += issue:

>> foo = []
=> []
>> def foo.[](i)
>>   fetch(i) {0}
>> end
=> nil
>> foo[4]
=> 0
>> foo
=> []
>> foo[4] += 123
=> 123
>> foo
=> [nil, nil, nil, nil, 123]

Update 3: this is starting to look like whack-a-mole!

>> foo
=> [nil, nil, nil, nil, 123]
>> foo[-2..-1]
TypeError: can't convert Range into Integer

But we can deal with that:

>> def foo.[](index)
>>   if index.is_a? Range
>>     index.map {|i| self[i] }
>>   else
?>     fetch(index) { 0 }  # default to 0 if no element at index; will not cause auto-extension of array
>>   end
>> end
=> nil
>> foo
=> [nil, nil, nil, nil, 123]
>> foo[-2..-1]
=> [nil, 123]

I now have to admit (sheepishly) that I'll subclass Array to avoid cluttering my code:

class MyClass
  class ArrayWithDefault < Array
    def [](index)
      if index.is_a? Range
        index.map {|i| self[i] }
      else
        fetch(index) { 0 }  # default to 0 if no element at index; will not cause auto-extension of array
      end
    end
  end
end

Thanks for all the creative solutions. TIMTOWTDI indeed!

4
  • 1
    If you need a sparse array, what's wrong with using a hash with integer keys?
    – Simon
    Mar 16, 2011 at 11:46
  • I wonder if any PHP developers have complained that their array/hash data structure doesn't exist in Ruby. Mar 16, 2011 at 12:40
  • Simon: I went with a hash in the first place, but there're a pain with some of the #maps and #injects I need to do. Mar 16, 2011 at 12:43
  • Andrew: quick, is this a hash or an array? foo[123] = 456 ;) Mar 16, 2011 at 12:44

7 Answers 7

160

Not auto extended, but initialized to the specified length with a default value:

>> Array.new(123, 0)  
=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1
  • 1
    Wouldn't that waste more memory?
    – Kunok
    Feb 12, 2017 at 23:22
22

Given that Ruby returns nil for a non-existing element (as opposed to index-out-of-bounds type error), you could just use an "or":

a = [1,2,3]
puts a[5]  # => nil
puts a[5] || "a default"  # => a default

You could take the monkey patch approach, but you probably would not want to do this in anything larger than a 1-file script:

a = [1,2,3]
def a.[](index)
  self.at(index) || "a default"
end
puts a[5]   # => "a default"
6
  • 9
    Or you could do a.fetch {"a default"}. Mar 16, 2011 at 12:47
  • Andrew: awesome! def foo.[](i); fetch(i) {0} end Mar 16, 2011 at 13:39
  • 1
    Andrew: also, I didn't know about the def obj.method syntax. Much nicer than obj.instance_eval { def method ... }! Mar 16, 2011 at 13:46
  • @Josh: That was by @Rob, not me. I just tidied up the indentation a little. Mar 16, 2011 at 22:21
  • 1
    The a[5] || "default" and a.fetch(5, "default") techniques mean that your client code needs to say what the default should be. It would be nice if Array worked like Hash, which provides a default_proc and default_value for missing keys.
    – Andrew Vit
    Oct 23, 2013 at 23:29
8

The easiest way would be:

new_array = Array.new(size, default_value)

For example:

new_array = Array.new(5,"foo")
4

Another approach would be overriding the Array#[] method and return the default value if there is no item

class Array         
  def [](index)
     self.at(index) ? self.at(index) : 0
  end
end

and

arr = [1,2,3]
puts arr[0]  # print 1
puts arr[5]  # print 0
2
  • I actually like this one, though rather than monkey-patching the Array class, I'll just instance_eval the override on the specific array I care about. Mar 16, 2011 at 12:42
  • This actually raises an error: TypeError: no implicit conversion of Range into Integer...
    – Victor
    May 27, 2018 at 4:46
3

I'll put Johans elegant solution out there: foo.compact.inject(:+)

0
3

If you're dealing with integers you can call to_i:

foo = []
foo[100]
#=> nil
foo[100].to_i
#=> 0
foo[100] = 3
foo[100]
#=> 3

UPD

Oh, I didn't read all topic :)

so you can use this:

foo.inject{|a,b| a.to_i + b.to_i }

which, actually, not the smartest one

1
  • Thank you, this was exactly what I needed.
    – snowe
    Apr 16, 2014 at 3:22
1

I think an array is the wrong abstraction if you want to auto extend the array. Add another level of abstraction.

Edit (from our discussion): The important thing is that the code to achieve your goal is located in the right place (single responsibility principle), and that place is not your "client code", hence the need for a new class. Extending the existing Array class (through inheritance/mixin) is probably better than encapsulating the wanted behaviour in an entierly new class.

7
  • 1
    Without knowing what I am doing, judging whether the abstraction is correct seems fairly impossible. Array auto-extension is a Ruby feature, so why would I want to build another layer of abstraction to accomplish the same thing as the default Array behaviour gives me? Ruby is not Java. ;) Mar 16, 2011 at 12:48
  • Agreed. What I am getting at is that you might want to encapsulate the extended behaviour in a class with a name that tells you what this class does rather than just monkey patch behaviour onto an existing class. This might be accomplished through inheritance/mixin or some other technique that ruby has. Mar 16, 2011 at 13:16
  • 1
    You are right though that I am a C++ programmer learning some Ruby rather than a Ruby guru :) Mar 16, 2011 at 13:18
  • Tobbe: hey, I've been there. My first Perl programs were basically C programs in Perl syntax, and my first Ruby ones were Perl in Ruby syntax. :) Mar 16, 2011 at 13:30
  • Tobbe (re encapsulation): I see your point about subclassing / mixing in to get a good name, but what I really want to do is change the behaviour of a specific Array instance, but preserve its Array-ness--i.e. the name "Array" is still the best description of its behaviour. Why should I need to subclass Array to get a default value when I don't need to subclass Hash for the same? Mar 16, 2011 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.