我需要Ruby方法将字符串数组转换为Hash,其中每个键都是一个字符串,每个值都是原始数组中字符串的1索引索引。
VideoCastConsumer myConsumer = new VideoCastConsumerImpl() {
void onVolumeChanged(double value, boolean isMute) {
// do as you wish here
}
}
VideoCastManager.getInstance().addVideoCastConsumer(myConsumer);
答案 0 :(得分:1)
def hashify(array)
array.each.with_index(1).to_h
end
hashify(%w(a b c))
#=> { "a" => 1, "b" => 2, "c" => 3 }
答案 1 :(得分:1)
即使我认为我正在帮助别人做功课,但我还是忍不住打高尔夫球,因为Ruby太棒了:
%w(a b c).each.with_index(1).to_h
另外,定义“hashify”非常类似于Ruby。我建议替代方案,但无论如何它可能是一个家庭作业,你似乎不想学习它。
答案 2 :(得分:0)
试试这个,这会向to_hash_one_indexed
类添加方法Array
。
class Array
def to_hash_one_indexed
map.with_index(1).to_h
end
end
然后调用它:
%w(a b c).to_hash_one_indexed
#=> {"a"=>1, "b"=>2, "c"=>3}
答案 3 :(得分:0)
(很明显)有多种方法可以在Ruby中实现目标。
如果您考虑表达式%w(a b c).map.with_index(1).to_h
,您可以看到将Enumerable类提供给我们的一些方法串联起来。
首先调用向数组发送:map消息,我们会收到一个Enumerator,它为我们提供了方便的:with_index方法。正如您在文档中看到的那样,with_index接受参数中的偏移量,因此将索引偏移1就像将参数传递给:with_index
一样简单。
最后,我们在枚举器上调用:to_h
来接收所需的哈希值。
# fore!
def hashify(array)
array.map.with_index(1).to_h
end
> hashify %w(a b c)
=> {"a"=>1, "b"=>2, "c"=>3}