0

How is mutation done in Ruby for this:

row = row.to_hash

I've tried row.to_hash!

But it doesn't work.

EDIT: Here is the code where it's in:

    CSV.foreach('stores.csv', :headers => true) do |row|
      row = row.to_hash
    end
8
  • 1
    Isn't this short enough already? In-place mutation of state may not be worth the 4 or so characters saved typing. Commented Nov 1, 2011 at 10:29
  • 1
    Your question is rather unclear. Which class is row a member of? What are you trying to achieve exactly? It would help if you could give an example value of row and then explain what you want the resulting hash to look like. Additionally, mutating variable types like this often impacts the legibility and maintainability of code; it might be better style to assign the hash to a new variable anyway. Commented Nov 1, 2011 at 10:33
  • @AdamSpiers: updated with the sample code. Commented Nov 1, 2011 at 10:40
  • @MichaelKohl: it's not just because it's short enough -- I'd like to see how mutation is done in Ruby. Commented Nov 1, 2011 at 10:41
  • 1
    I think this is a fairly reasonable question. The asker clearly states he or she is a beginner and there is an underlying reason for hiding mutation in some cases. It is interesting to discuss what those reasons are in order to learn more about the language. Commented Nov 1, 2011 at 11:15

2 Answers 2

2

Unless I misunderstand your question you might try:

rows = []
CSV.foreach('stores.csv', :headers => true) do |row|
  rows << row.to_hash
end

It's not actually mutation, but it does give you the output you seem to be looking for. One of the reasons for having separate methods for performing an action for new output vs. changing data in place is that in general it is wiser to have your input data be immutable. Reading from a CSV file probably doesn't fit into this paradigm cleanly (the original input is in a file somewhere), which is likely why there's no ! version of to_hash.

Optionally in my above code you could just process the hash and put the results where you want it if the input file is humongous in order to save space, rather than just shoving all the hashes into the array and then processing that array.

Sign up to request clarification or add additional context in comments.

Comments

-1

We actually can't say if there is such a method. But it's most likely there isn't one, if you get a NoMethodError. :)

6 Comments

It is indeed a rails function. Here
Well, that's from the FlashHash class. I don't think you're using that one.
I don't even know what your statement is right now. Can you clarify on that?
It converts a row from a csv file into a hash using the header row. It's built into Rails 3.1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.