Created
January 31, 2017 17:02
-
-
Save haiitch/9317a848ea480db8635dff192c156480 to your computer and use it in GitHub Desktop.
module Lookupable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Either as a mixin or a separate implementation for Array and Hash | |
# this feels like something that should be in Ruby core. | |
# A better implementation of this, obviously, with identical functionality | |
module Lookupable | |
def lookup(lookupindex,lookupvalue,returnindex) | |
isarray = self.class == Array | |
self.each_with_index {|element,index| | |
record = isarray ? element : element.last | |
if record[lookupindex]==lookupvalue then | |
return record[returnindex] | |
end | |
} | |
return nil | |
end | |
end | |
class Array | |
include Lookupable | |
end | |
class Hash | |
include Lookupable | |
end | |
a = [ ["Mercury", "Hg", 80, 200.592 ], | |
["Argon", "Ar", 18, 39.948 ], | |
["Chromium","Cr", 24, 51.9961] ] | |
a.lookup(1,"Ar",3) # returns atomic weight of Argon | |
h = { "Hg" => { name: "Mercury", atomicno: 80, weight: 200.592 }, | |
"Ar" => { name: "Argon", atomicno: 18, weight: 39.948 }, | |
"Cr" => { name: "Chromium", atomicno: 24, weight: 51.9961} } | |
# Return the name of the element whose atomic number is 18 | |
h.lookup(:atomicno,18,:name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment