How to map with index in Ruby?

If you’re using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do: In 1.8.6 you can do:

Ruby: undefined method `[]’ for nil:NilClass when trying to get Enumerator on an Array of Hashes

undefined method `[]’ for nil:NilClass says you tried to do something[index] but something is nil. Ruby won’t let you use nil as an array (ie. call the [] method on it). The problem is not on the attributs.each line but on the line following which calls the [] method on attribut. This indicates something in … Read more

Array to Hash Ruby

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 … Read more

How to read lines of a file in Ruby

153 I believe my answer covers your new concerns about handling any type of line endings since both “\r\n” and “\r” are converted to Linux standard “\n” before parsing the lines. To support the “\r” EOL character along with the regular “\n”, and “\r\n” from Windows, here’s what I would do: Of course this could be a bad idea on very large files since it means … Read more

What does ||= (or-equals) mean in Ruby?

This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing-list that discuss this issue. Here’s one: The definitive list of ||= (OR Equal) threads and pages If you really want … Read more