Reputation: 3721
I want a method to create the following json string in many places:
{"daily_calendar":{"search":{"print_date":"2014-06-30"}}}
I have following four lines of code to make the hash:
custom_params, print_date, search = Hash.new, Hash.new, Hash.new
print_date['print_date'] = @week_day
search['search'] = print_date
custom_params['daily_calendar'] = search
puts custom_params.to_json
What is the best way to do it in one or two lines and use it anywhere in the controller?
Upvotes: 1
Views: 62
Reputation: 110675
A recursive expression allows you to have any number of nested hashes:
def doit(*h,v)
h.size == 1 ? { h.first => v } : { h.shift => doit(*h,v) }
end
h = %w[one_more_level daily_calendar search print_date]
doit(*h, 'tue')
#=> {"one_more_level"=>{"daily_calendar"=>{"search"=>{"print_date"=>"tue"}}}}
Upvotes: 1
Reputation: 14082
Just write as it is:
hash = {daily_calendar: {search: {print_date:@week_day} } }
puts hash.to_json
Upvotes: 2
Reputation: 224903
You can use hash literals:
custom_params = {
"daily_calendar" => {
"search" => {
"print_date" => @week_day
}
}
}
Upvotes: 1