首页  >  问答  >  正文

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

全部回复(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
  • 取消回复