Can I create an array in Ruby with default values?

前端 未结 7 696
你的背包
你的背包 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:15

    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.

提交回复
热议问题