Ruby - 将字符串转换为哈希值,每个字符作为键,索引作为值?

Igg*_*ggy 0 ruby hash

我试图将给定的字符串转换为散列,每个字符串的字符= key和index = value.

例如,如果我有str = "hello",我希望它转变为{"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

我创建了一个方法:

def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
Run Code Online (Sandbox Code Playgroud)

问题是它跳过了第一个l.如果我颠倒了elindex: 的顺序arr.map.with_index {|el, index| [index, el]}.to_h,我会把所有字母拼写出来:{0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

但是当我invert这样做时,我会得到同样的哈希,跳过其中一个l.

map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
Run Code Online (Sandbox Code Playgroud)

为什么这样表现如此?我怎么才能打印出来{"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}

ste*_*lag 6

它可以完成,但会混淆其他Ruby程序员.普通哈希将键"a"视为与另一个"a"相同.除非使用一些鲜为人知的功能.compare_by_identity:

h = {}.compare_by_identity
"hello".chars.each_with_index{|c,i| h[c] = i}
p h    # => {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}
Run Code Online (Sandbox Code Playgroud)

  • "但会混淆其他Ruby程序员." 这是不使用它的一个很好的理由,除非周围有大的警示标志. (2认同)
  • `h["l"] # => nil` :-/ (2认同)