params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
opts = {}
opts[:a] = params[:a]
opts[:b] = params[:b]
opts[:c] = params[:c]
foo( opts )
Refactorings
No refactoring yet !
Vanson Samuel
May 21, 2010, May 21, 2010 02:36, permalink
Hash[*{:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }.collect { |k, v|
[k, v] if [:a, :b, :c].include?(k)
}.compact.flatten]
Kevin Ingolfsland
May 21, 2010, May 21, 2010 02:53, permalink
This seems to work, but it doesn't seem to be very clear.
params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
foo( params.clone.delete_if { |k,v| not [:a, :b, :c].include?(k) } )
pepepe
May 21, 2010, May 21, 2010 05:39, permalink
class Hash
def only(array=[])
r = {}
array.each do |k|
r[k] = self[k]
end
r
end
end
foo(params.only [:a, :b, :c])
drTheMan
May 21, 2010, May 21, 2010 12:34, permalink
reject is clone.delete_if combined into one handy method ;)
params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
foo params.reject{|key,value| ![:a,:b,:c].include?(key)}
vitaly
May 27, 2010, May 27, 2010 01:09, permalink
params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
class Hash
def only(*slice)
reject {|key,value| !slice.include?(key)}
end
end
foo params.only(:a, :b, :c)
Sam Warmuth
May 28, 2010, May 28, 2010 05:47, permalink
I'm surprised no one used select yet
params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
foo params.select{|k| [:a, :b, :c].include?(k)}
Dragan Cvetinovic
June 18, 2010, June 18, 2010 11:26, permalink
I like the brevity of the select solution, it is the best I think.
I came up with a just another one , not as good as with the select.
Also , Rails has slice and slice! methods for the same purpose...
params = {:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }
foo Hash[*(params.keys & [:a, :b, :c]).inject([]){|a, k| a << k << params[k]}]
#or
foo Hash[*[:a, :b, :c].inject([]){|a,k| params[k] ? a << k << params[k] : a}]
I only want the keys :a, :b, :c to be passed into the function foo