要散列的 Ruby 数组:每个元素都是键并从中派生出值 [英] Ruby array to hash: each element the key and derive value from it

查看:27
本文介绍了要散列的 Ruby 数组:每个元素都是键并从中派生出值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,想用它来做一个散列.数组的每个元素都是键,我想根据该键计算出值.有没有 Ruby 方法可以做到这一点?

I have an array of strings, and want to make a hash out of it. Each element of the array will be the key, and I want to make the value being computed from that key. Is there a Ruby way of doing this?

例如:

['a','b'] 转换为 {'a'=>'A','b'=>'B'}

推荐答案

Ruby 的 each_with_object 方法是做你想做的事情的巧妙方法

Ruby's each_with_object method is a neat way of doing what you want

['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }

这篇关于要散列的 Ruby 数组:每个元素都是键并从中派生出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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