55502f40dc8b7c769880b10874abc9d0

I only want the keys :a, :b, :c to be passed into the function foo

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 !

9fe6d04c7c6a357a92a2b05efd0d09bc

Vanson Samuel

May 21, 2010, May 21, 2010 02:36, permalink

No rating. Login to rate!
Hash[*{:a => "a", :b => "thisisb", :c => "c", :d => "thiswasb", :e => "34" }.collect { |k, v|
	[k, v] if [:a, :b, :c].include?(k)
}.compact.flatten]
1e3812190445556c1b2d10f0d0810dba

Kevin Ingolfsland

May 21, 2010, May 21, 2010 02:53, permalink

No rating. Login to rate!

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) } )
D41d8cd98f00b204e9800998ecf8427e

pepepe

May 21, 2010, May 21, 2010 05:39, permalink

No rating. Login to rate!
class Hash
  def only(array=[])
    r = {}
    array.each do |k|
      r[k] = self[k]
    end
    r
  end
end

foo(params.only [:a, :b, :c])
D41d8cd98f00b204e9800998ecf8427e

drTheMan

May 21, 2010, May 21, 2010 12:34, permalink

3 ratings. Login to rate!

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)}
996b64c2708771eb4f0c479e0d3a0646

vitaly

May 27, 2010, May 27, 2010 01:09, permalink

1 rating. Login to rate!
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)
Cb9b01bd3f65603f3314b71b868a3703

Sam Warmuth

May 28, 2010, May 28, 2010 05:47, permalink

2 ratings. Login to rate!

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)}
36ad787d1b5306e65e89b441e0cade8f

Dragan Cvetinovic

June 18, 2010, June 18, 2010 11:26, permalink

No rating. Login to rate!

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}]

Your refactoring





Format Copy from initial code

or Cancel