【问题标题】:Is there a way to inject into a hash in coffescript, just like in Ruby?有没有办法像在 Ruby 中一样注入到咖啡脚本中的哈希中?
【发布时间】:2013-01-11 19:57:44
【问题描述】:

在 Ruby 中,我可以这样做:

hash = ['foo', 'bar'].each_with_object({}) { |i, h| h[i] = 0 }

我如何在 CoffeeScript 中做同样的事情,最好使用一些优雅的单线?

【问题讨论】:

    标签: ruby coffeescript


    【解决方案1】:

    一种方法是这样的:

    hash = {}
    hash[key] = 0 for key in ["foo", "bar"]
    

    另外,在 Ruby 示例中,您可以使用 each_with_object 代替 inject,这样您就不需要在末尾返回 h 变量:

    hash = ['foo', 'bar'].each_with_object({}) { |i, h| h[i] = 0 }
    

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 2013-03-03
      • 1970-01-01
      • 2016-06-27
      • 2014-01-20
      • 1970-01-01
      • 2015-02-23
      • 2011-11-04
      • 2013-01-17
      相关资源
      最近更新 更多