开发者

How do I create three objects with one line of code?

How would I create three empty hashes with a single line o开发者_如何转开发f code?

I know that a = b = c = Hash.new won't work, since that'll create three references to the same Hash object.

a,b,c = Hash.new will assign the Hash to a, but b and c remain nil.

I know I could do a, b, c = Hash.new, Hash.new, Hash.new, but that doesn't look very DRY.


As I posted as a comment, I think a, b, c = {}, {}, {} is the best way, because it's short, and easy to read. If you really want to do it in a more complicated way, something like this will work:

>> a, b, c = Array.new(3) { Hash.new } #=> [{}, {}, {}]
>> a #=> {}
>> b #=> {}
>> c #=> {}


I am not really sure if I would use that, but it is possible:

a, b, c = 3.times.map { Hash.new }
# or
a, b, c = (1..3).map { Hash.new }


Although you already marked an answer, I'd throw in another way which I find as the simplest one:

a,b,c = [{}]*3


I am not really sure if I would use that, but it is possible:

a, b, c = 3.times.map { Hash.new }
#or
a, b, c = (1..3).map { Hash.new }

And yet another answer.. since you can simply use {} instead of Hash.new The assignation could be like this:

a, b, c = 3.times.map{{}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜