Home  >  Q&A  >  body text

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

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

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

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

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

PHPzPHPz2713 days ago870

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-21 11:21:07

    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. .

    reply
    0
  • Cancelreply