Can I create an array in Ruby with default values?

前端 未结 7 708
你的背包
你的背包 2020-12-14 14:58

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\         


        
7条回答
  •  没有蜡笔的小新
    2020-12-14 15:32

    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"
    

提交回复
热议问题