Ruby:什么是最简单的方法来更新哈希值? [英] Ruby: What is the easiest method to update Hash values?

查看:84
本文介绍了Ruby:什么是最简单的方法来更新哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说:

  h = {1 => 10,2 => 20,5 => 70,8 => 90,4 => 34} 

我想改变每个值 v foo(v ),这样 h 将会是:

  h = {1 => foo(10),2 => foo(20),5 => foo(70),8 => foo(90),4 => foo(34)} 

达到此目的的最优雅方式是什么?

解决方案

您可以使用更新(别名 merge!

  hash.update(hash){| key,value | c $ c>)用块更新每个值:值* 2} 

请注意,我们正在有效地合并 hash 与自己。这是必需的,因为Ruby会调用该块来解决碰撞的任何键的合并,并将该值设置为该块的返回值。

Say:

h = { 1 => 10, 2 => 20, 5 => 70, 8 => 90, 4 => 34 }

I would like to change each value v to foo(v), such that h will be:

h = { 1 => foo(10), 2 => foo(20), 5 => foo(70), 8 => foo(90), 4 => foo(34) }

What is the most elegant way to achieve this ?

解决方案

You can use update (alias of merge!) to update each value using a block:

hash.update(hash) { |key, value| value * 2 }

Note that we're effectively merging hash with itself. This is needed because Ruby will call the block to resolve the merge for any keys that collide, setting the value with the return value of the block.

这篇关于Ruby:什么是最简单的方法来更新哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆