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]"}
@stuliston
Copy link

data.slice(:name, :email)

Oh, that's cheating - it's an Active Support core extension ;-)

I't must be possible to do it more concisely than this:

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

@jdunwoody
Copy link

data.except(:age, :address)

@timothydang
Copy link

_.pick(data, 'name', 'email')

@stuliston Oh, it's cheating as well. it's javascript!!!

@ashmckenzie in fairness, I only added the 'using Ruby stdlib' after this :)

@stuliston
Copy link

That's an interesting method, @jdunwoody...

@markba
Copy link

markba commented Oct 1, 2013

I made this just for you Ash. Extra special taco bell code.

!/bin/bash

NAME=cat test |tail +2 | cut -d: -f2 |cut -d\' -f2|head -1
EMAIL=cat test |tail +5 | cut -d: -f2 |cut -d\' -f2|head -1
echo "{:name=>$NAME, :email=>$EMAIL}"

*'test' is the input file
*this is a joke, but it works

@ashmckenzie Code named 'Fiery Doritos Locos Tacos Supreme'

@pmoran
Copy link

pmoran commented Oct 1, 2013

data.delete_if {|k| [:age, :address].include? k}

@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