在Ruby中,如何在Hash中交换密钥?
假设我有以下哈希:
{:one=>1, :two=>2, :three=>3, :four=>4 }
Run Code Online (Sandbox Code Playgroud)
我想转变成:
{:one=>1, :three=>2, :two=>3, :four=>4}
Run Code Online (Sandbox Code Playgroud)
也就是说,交换密钥:两个和三个但保持其值不变.
什么是最有效的解决方案?
最简单的方法是:
h = {:one => 1, :two => 2, :three => 3, :four => 4}
h[:two], h[:three] = h[:three], h[:two]
Run Code Online (Sandbox Code Playgroud)
如果这是您需要定期执行的操作,则可以在Hash上定义一个允许更漂亮的语法的方法:
class Hash
def swap!(a, b)
self[a], self[b] = self[b], self[a] if key?(a) && key?(b)
self
end
def swap(a, b)
self.dup.swap!(a, b)
end
end
Run Code Online (Sandbox Code Playgroud)
但请注意,这两种解决方案都将保留散列中键值对的顺序.如果要实际交换密钥及其值,可以执行以下操作:
class Hash
def swap(a, b)
self.inject(Hash.new) do |h, (k,v)|
if k == a
h[b] = self[a]
elsif k == b
h[a] = self[b]
else
h[k] = v
end
h
end
end
end
{:one => 1, :two => 2, :three => 3, :four => 4}.swap(:two, :three)
# results in {:one=>1, :three=>2, :two=>3, :four=>4}
Run Code Online (Sandbox Code Playgroud)
虽然我不确定你为什么要那样做.
| 归档时间: |
|
| 查看次数: |
815 次 |
| 最近记录: |