Skip to content

Instantly share code, notes, and snippets.

@ashmckenzie
Last active December 24, 2015 08:59
Show Gist options
  • Save ashmckenzie/6774234 to your computer and use it in GitHub Desktop.
Save ashmckenzie/6774234 to your computer and use it in GitHub Desktop.
Create the smallest solution to take the given data hash and produce the desired output (using pure Ruby stdlib)
# Source data
#
data = {
name: 'John Smith',
age: 45,
address: '123 Here St',
email: '[email protected]'
}
# Code here..
# Desired output
#
# {:name=>"John Smith", :email=>"[email protected]"}
@clouseauu
Copy link

Building on @pmoran's, but in the opposite way, assuming you know what you want and not necessarily what you don't want:

data.keep_if {|k| [:name, :email].include? k}

@ashmckenzie
Copy link
Author

data.select { |k,v| k =~ /^(n|e)/ }

@ashmckenzie absolutely shameful :)

@gabrielrotbart
Copy link

@ashmeckenzie neat!

Because all the neat solutions were taken (I was going with Stu). I give you:

[:name, :email].map {|k| Hash[k, data[k]] }.inject(:update)

@ashmckenzie BAM, #map and #inject !

@gabrielrotbart obfuscation is the best solution

@stuliston
Copy link

Here's the winning solution*

> data.win
=> {:name=>"John Smith", :email=>"[email protected]"}

*assuming you're using my personally-patched ruby

class Hash
  def win
    {:name=>"John Smith", :email=>"[email protected]"}
  end
end

face palm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment