Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to fill a Ruby hash?

Tags:

ruby

hash

Is there a better way to do this? (it looks clunky)

form_params = {}
form_params['tid'] = tid
form_params['qid'] = qid
form_params['pri'] = pri
form_params['sec'] = sec
form_params['to_u'] = to_u
form_params['to_d'] = to_d
form_params['from'] = from
form_params['wl'] = wl
like image 447
Bruno Antunes Avatar asked May 08 '09 14:05

Bruno Antunes


2 Answers

form_params = { "tid" => tid, "qid" => qid }     

Or you could do

form_params = Hash["tid", tid, "qid", qid]       #=> {"tid"=>tid, "qid"=>qid}
form_params = Hash["tid" => tid, "qid" => qid]   #=> {"tid"=>tid, "qid"=>qid}
form_params = Hash[tid => tid, qid => qid]       #=> {"tid"=>tid, "qid"=>qid}

(nb. the last one is new for 1.9 and it makes your key symbols instead of strings)

{tid:tid, qid:qid}

Keys and values occur in pairs, so there must be an even number of arguments.

like image 140
Schildmeijer Avatar answered Sep 25 '22 07:09

Schildmeijer


Slight modification to the above, since your example had string keys:

form_params = {}
%w(tid qid pri sec to_u to_d from wl).each{|v| form_params[v] = send(v)} 
like image 26
ry. Avatar answered Sep 25 '22 07:09

ry.