English 中文(简体)
页: 1
原标题:Ruby: inject issue when turning array into hash
  • 时间:2012-05-13 20:41:47
  •  标签:
  • ruby
a = [[1,  a ],[2,  b ],[3,  c ], [4,  d ]]
a.inject({}) {|r, val| r[val[0]] = val[1]}

When I run this, I get an index error

当我改变僵局时

a.inject({}) {|r, val| r[val[0]] = val[1]; r}

然后,它运作。

How is ruby handling the first inject attempt that isn t getting what I want?
Is there a better way to do this?

最佳回答

仅仅因为鲁比语是动态的,而且含蓄的,并不意味着你不必考虑种类。

如果没有明确的加固剂(通常称为<条码>缩略语/代码>)的<代码>可观的#inject就属于这种情况。

reduce :: [a] → (a → a → a) → a

或者说,我只是由另一个人组成。

Enumerable[A]#inject {|A, A| A } → A

你会注意到,所有类型都是相同的。 <代码>可计算的要素类型、两个论点类型、组群的返回类型和总方法的返回类型。

fold :: [b] → a → (a → b → a) → a

Enumerable[B]#inject(A) {|A, B| A } → A

Here you see that the accumulat或 can have a different type than the element type of the collection.

这两项规则一般都通过所有<条码>获得。 与类型有关的问题:

  1. the type of the accumulat或 and the return type of the block must be the same
  2. when not passing an explicit accumulat或, the type of the accumulat或 is the same as the element type

在这种情况下,是第1条。 当你做这样的事情时,你会这样做。

acc[key] = value

在您的栏目中,任务评价的是分配价值,而不是任务接收者。 页: 1

acc.tap { acc[key] = value }

另见。 为什么没有初步价值,鲁比拉的注射方法不能将扼杀时间加在一起?


BTW: you can use destructuring bind to make your code much m或e readable:

a.inject({}) {|r, (key, value)| r[key] = value; r }
问题回答

比较容易的方式——

a = [[1,  a ],[2,  b ],[3,  c ], [4,  d ]]
b = Hash[a] # {1=>"a", 2=>"b", 3=>"c", 4=>"d"}

第一种方法为t工作,其原因是,在下一个版本中,注射使用作为<代码>r的整块结果。 首先,<代码>r,请查阅您通过的论点,此处为{}

a.inject({}) { |r, val| r.merge({ val[0] => val[1] }) }




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签