1

I want to generate a JSON object while fetching data from database.

def duration
  return @data[:duration] unless @data[:duration].nil?

  @data[:duration] = per_hour.collect do | val |
    [val[0], val[1]]
  end
end

I get the data I need, but the array isn't correct. My view looks like:

var array = <%= raw @duration_data.to_json %>;

And my array looks like this:

var array = [{"data": [[0,0],[1,60.0]] }];

But what I need is this:

var array = [{"data": {"0":0, "1":60.0} }];

3 Answers 3

2

You just need to convert your array to a hash:

@data[:duration] = per_hour.collect do |val|
  [val[0], val[1]]
end.to_h

For Ruby 1.9:

@data[:duration] = Hash[*per_hour.collect { |val| [val[0], val[1]] }]
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, but I got this error undefined method `to_h' for [[0, 3]]:Array
You probably have an old Ruby version, I will correct the answer
No I'm running with rails 2.1
This has nothing to do with rails, you need to check your ruby version. You can do this in your project root by typing ruby --version in your console
1

I would write this as follows:

def duration
  @data[:duration] ||= build_duration
end 

This is a short way to say: return @data[:duration] if not nil, otherwise, assign build_duration to it.

And then you define build_duration

def build_duration
  result = {}
  per_hour.each do |val|
    result[val[0]] = val[1]
  end
  result
end

You can write the build_duration more compact, but for me this is very readable: it will build a hash and fill it up as you wish.

Comments

1
@data[:duration] ||= per_hour.collect { | val | [val[0], val[1]] }.to_h

Try this.

2 Comments

I got this error: undefined method `to_h' for [[0, 3]]:Array
This should return pry(main)> [[0, 3]].to_h => {0=>3}

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.