数组散列红宝石 [英] Array to Hash Ruby

查看:117
本文介绍了数组散列红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以这里的交易,我一直在使用Google的年龄找到一个解决方案,这一点,同时也有许多在那里,他们似乎没有做我在找工作。

基本上我有结构类似这样的数组

  [项目1,项目2,3项,项目4]

我想将其转换为一个哈希,所以它看起来像这样

  {项目1=> 项目2,项目3=> 第4项}

即。这是在偶指标的项目是键,在奇索引项的值。

任何想法如何干净地做到这一点?我想蛮力方法是直接拔掉所有连索引到一个单独的数组,然后循环周围添加值。


解决方案

  A = [项目1,项目2,3项,项目4]
H =散列[* A]#=> {项目1=> 项目2,项目3=> 第4项}

就是这样。在 * 被称为图示的运营商。


每@Mike刘易斯一个警告(在评论)。要非常小心这个红宝石堆栈上展开的提示图标如果你这样做有一个大的数据集,希望吹出来你的筹码

因此​​,对于大多数一般用途的情况下这种方法是伟大的,但如果你想要做的大量数据转换使用不同的方法。例如,@卢卡斯Niemier(也在评论)提供了这种方法对于大数据集:

  H =散列[a.each_sli​​ce(2).to_a]

Okay so here's the deal, I've been googling for ages to find a solution to this and while there are many out there, they don't seem to do the job I'm looking for.

Basically I have an array structured like this

["item 1", "item 2", "item 3", "item 4"] 

I want to convert this to a Hash so it looks like this

{ "item 1" => "item 2", "item 3" => "item 4" }

i.e. the items that are on the 'even' indexes are the keys and the items on the 'odd' indexes are the values.

Any ideas how to do this cleanly? I suppose a brute force method would be to just pull out all the even indexes into a separate array and then loop around them to add the values.

解决方案

a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }

That's it. The * is called the splat operator.


One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."

So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Łukasz Niemier (also in the comments) offers this method for large data sets:

h = Hash[a.each_slice(2).to_a]

这篇关于数组散列红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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