Last active
September 6, 2016 06:44
-
-
Save bastman/02fb27e0dd776096e997f0e93450b402 to your computer and use it in GitHub Desktop.
Ruby Hash: simple immutable Hash.map() implementation for old ruby versions
This file contains hidden or 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
class Hash | |
def map_kv(&block) | |
result_hash = Hash.new() | |
for k,v in self | |
result_item=block.call(k,v) | |
result_hash[result_item.fetch("key")]=result_item.fetch("value") | |
end | |
return result_hash | |
end | |
def map_v(&block) | |
result_hash = Hash.new() | |
for k,v in self | |
result_hash[k]=block.call(k,v) | |
end | |
return result_hash | |
end | |
def map_k(&block) | |
result_hash = Hash.new() | |
for k,v in self | |
result_hash[block.call(k,v)]=v | |
end | |
return result_hash | |
end | |
end | |
puts "======" | |
dict={"a":"A", "b":"B"} | |
puts dict | |
# map (key, value) | |
dict1=dict.map_kv{ |k,v| | |
{"key"=>k.to_s+"K1", "value"=>v+"V1"} | |
} | |
puts dict1 | |
# map (key) | |
dict2=dict.map_k{ |k,v| | |
k.to_s+"K2" | |
} | |
puts dict2 | |
# map (value) | |
dict3=dict.map_v{ |k,v| | |
v+"V3" | |
} | |
puts dict3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment