ruby-on-rails - 想要翻译一段ruby的代码,有两句看不懂
PHPz
PHPz 2017-04-21 11:19:07
0
1
929
  1. @item_array = Hash.new { |hash| hash = Hash.new(false) }
  2. @item_array[i] = [] unless @item_array.member? sindex;

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

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

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

PHPz
PHPz

学习是最好的投资!

reply all(1)
Peter_Zhu

First question: http://ruby-doc.org/core-2.1.0/Hash.html#method-c-new
Let’s write a few more sentences. There are two ways to use it

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

or

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

Actually, the hash = Hash.new(false); written in the question is completely unnecessary. The meaning of this sentence is actually
Actually I just want

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

is enough.

Second question: If item_array does not have a member with symbol sindex, then execute the previous @item_array[i] = []. This syntax is to post clauses such as if (or while unless). What it expresses is actually

xxx if condition

=>

if condition
  xxx
end

Essentially, there are a few lines missing. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template