ruby-on-rails - 想要翻译一段ruby的代码,有两句看不懂

浏览:42日期:2022-10-21

问题描述

@item_array = Hash.new { |hash| hash = Hash.new(false) }@item_array[i] = [] unless @item_array.member? sindex;

第一句觉得很奇怪啊,没理解错的话是创建了一个二维hash表吧。但是很不解的是为什么ruby的hash可以给定一个初始值?只有值吗?键呢?键在哪儿?

第二句那个unless很绕啊,真搞不懂为啥要有这样的关键字,那句话意思是说: 除非存在sindex这个键,我赋值为[],否则。。。得,按我这样理解这个“否则”还不知道要干嘛!?

请大家帮我看看吧,先谢谢啦。

问题解答

回答1:

第一个问题:http://ruby-doc.org/core-2.1.0/Hash.html#method-c-new在多写几句吧,这里的用法可以用两种

xxx = Hash.new { |hash| Hash.new(false) }

或者

xxx = Hash.new { |hash,key | hash[key] = Hash.new(false);nil }

实际上,问题上面写的hash = Hash.new(false);是完全没有必要的,这句的意思其实是其实我只要

Hash.new { Hash.new(false);}

就足够了。

第二个问题:如果item_array不存在符号为sindex的成员,那就执行前面的@item_array[i] = []。这个语法是把if(或则while unless)之类的子句后置。表达的其实是

xxx if condition

=>

if condition xxxend

本质上就是少了几行。。

相关文章: