【问题标题】:Array to Hash or 2 binary element Array数组到哈希或 2 个二进制元素数组
【发布时间】:2009-10-20 05:25:17
【问题描述】:

我正在寻找最简洁的方法

给定以下数组:

['a','b','c']

如何获得:

{'a'=> 1,'b'=> 2, 'c'=> 3}

[['a',1],['b',2],['c',3]]

我想到的解决方案很少,只是想看看你的:)

【问题讨论】:

    标签: ruby arrays hash


    【解决方案1】:
    a.zip(1..a.length)
    

    Hash[a.zip(1..a.length)]
    

    【讨论】:

    • 不,这两个都会引发“无法将范围转换为数组”。你必须为第一个做“a.zip((1..a.size).to_a)”,然后在第二个中引发“哈希的奇数个参数”,所以你必须做 Hash[ *...展平]。
    【解决方案2】:
    # 1.8.7+:
    ['a','b','c'].each_with_index.collect {|x,i| [x, i+1]} # => [["a", 1], ["b", 2], ["c", 3]]
    # pre-1.8.7:
    ['a','b','c'].enum_with_index.collect {|x,i| [x, i+1]}
    
    # 1.8.7+:
    Hash[['a','b','c'].each_with_index.collect {|x,i| [x, i+1]}] # => {"a"=>1, "b"=>2, "c"=>3}
    # pre-1.8.7:
    Hash[*['a','b','c'].enum_with_index.collect {|x,i| [x, i+1]}.flatten]
    

    【讨论】:

    • “enum_with_index”是什么时候引入的?它在 1.8.5 中不存在!
    【解决方案3】:

    如果你想要简洁快速,以及 1.8.5 的兼容性,这是我想出的最好的:

    i=0
    h={}
    a.each {|x| h[x]=i+=1}
    

    适用于 1.8.5 的 Martin 版本是:

    Hash[*a.zip((1..a.size).to_a).flatten]
    

    但这比上面的版本慢了 2.5 倍。

    【讨论】:

      【解决方案4】:
      aa=['a','b','c']
      => ["a", "b", "c"]    #Anyone explain Why it became double quote here??
      
      aa.map {|x| [x,aa.index(x)]}   #assume no duplicate element in array
      => [["a", 0], ["b", 1], ["c", 2]]
      
      Hash[*aa.map {|x| [x,aa.index(x)]}.flatten]
      => {"a"=>0, "b"=>1, "c"=>2}
      

      【讨论】:

      • "#Anyone解释为什么这里变成双引号??" - 你希望 Ruby 记住字符串最初是使用单引号还是双引号创建的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 2014-04-18
      • 2019-07-30
      • 1970-01-01
      • 2021-08-01
      • 2016-07-16
      • 2011-12-14
      相关资源
      最近更新 更多