Can I create an array in Ruby with default values?

前端 未结 7 697
你的背包
你的背包 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 15:30

    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
    

提交回复
热议问题