首頁  >  問答  >  主體

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 天前871

全部回覆(1)我來回復

  • 天蓬老师

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

    第一個問題: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
      xxx
    end
    

    本質上就是少了幾行。 。

    回覆
    0
  • 取消回覆