How do I convert a hash's values into lambdas recursively? - ruby

I have a Hash that looks like this:
{
:a => "700",
:b => "600",
:c => "500",
:d => "400",
:e => "300",
:f => {
:g => "200",
:h => [
"test"
]
}
}
my goal is to iterate over this hash and return a copy that have all the values wrapped in a lambda, similar to this: https://github.com/thoughtbot/paperclip/blob/dca87ec5d8038b2d436a75ad6119c8eb67b73e70/spec/paperclip/style_spec.rb#L44
I went with each_with_object({}) but best I can do is to wrap only the first level, so I tried to check when I meet another Hash in the cycle (:f in this case, only it's key's values should be a lambda unless they are a hash as well) and treat it, but it's becoming quite troublesome.

def hash_values_to_lambda(old_hash)
{}.tap do |new_hash|
old_hash.each do |key, value|
new_hash[key] =
if value.is_a?(Hash)
hash_values_to_lambda(value)
else
lambda { value } # or -> { value } with new syntax
end
end
end
end
If you want, you can go with each_with_object instead of tap:
old_hash.each_with_object({}) do |(key, value), new_hash|
# everything else remains the same
end

Related

Incrementation in Ruby hashes

I'm trying to increment the key in a hash. For example. I'm trying to get this
{:b => "crayons", :c => "colors", :d => "apples"}
to turn into this
{:c => "crayons", :d => "colors", :e => "apples"}
I thought this code would do the trick but it doesn't. What do I need to change?
def hash(correct)
mapping = correct.each{|key, element| key.next}
Hash[correct.map {|key, element| [mapping[key], element]}]
end
Using Enumerable#each_with_object
def hash_correct(hsh)
hsh.each_with_object({}) { |(k,v), hsh| hsh[k.succ] = v }
end
hash_correct({:b => "crayons", :c => "colors", :d => "apples"})
# => {:c=>"crayons", :d=>"colors", :e=>"apples"}
def hash(correct)
Hash[correct.map{|key, element| [key.next, element]}]
end
h = {:b => "crayons", :c => "colors", :d => "apples"}
h.keys.map(&:succ).zip(h.values).to_h
#=> {:c=>"crayons", :d=>"colors", :e=>"apples"}
If the intent were to modify (not keep) the original hash, the update could be done in place:
keys = h.keys.reverse
keys.each { |k| h[k.succ] = h[k] }
h.delete(keys.last)
which could be inscrutablized to:
h.delete(h.keys.reverse.each { |k| h[k.succ] = h[k] }.last)
def hash(correct)
exp_hash = correct.map { | k, v| {k.next => v} }
Hash[*exp_hash.collect{|h| h.to_a}.flatten]
end
correct = {:b => "crayons", :c => "colors", :d => "apples"}
I thought this code would do the trick but it doesn't.
mapping = correct.each{|key, element| key.next}
If you go to the ruby Symbol docs and click on the link for next()...surprise there is no entry for next, but the description at the top of the window says:
succ
Same as sym.to_s.succ.intern.
From that you have to deduce that next() is a synonym for succ(). So Symbol#next/succ converts the symbol to a string by calling to_s(). Well, you know that you are going to get a String returned from to_s, and no matter what you do to that String, e.g. calling String#succ on it, it isn't going to effect some Symbol, e.g. your hash key. Furthermore, if you look at the docs for String#succ, it says
succ -> new_string
...so String#succ creates another String object and calling intern() on that String object, and by the way intern() is just a synonym for to_sym(), once again won't affect some Symbol...and it won't even affect the String object returned by to_s.
Finally, intern() doesn't change the second string object but instead returns a Symbol:
a String
V
key.next => key.to_s.succ.intern => Symbol
^
another String
...and because you didn't do anything with the Symbol returned by intern(), it is discarded.

method similar to array#pop for hash

I have a hash of people keyed by job and sorted by salary:
person = Struct.new(:salary)
people = {
:butchers => [
person.new(10),
person.new(6),
person.new(4)
],
:bakers => [
person.new(16),
person.new(8),
person.new(7)
],
:candlestick_makers => [
person.new(25),
person.new(21),
person.new(18)
]
}
I want to remove the last x people of each job from their respective array and do something:
def this_example_method
people.each do |job, people|
people.pop(number_for(job)).each do |person|
#do something
end
end
end
the 'do something' works okay, but pop removal doesn't. After running this_example_method, the people hash should look this, but at the moment it's not changing:
people = {
butchers = [
<butcher_1 salary:10>
<butcher_2 salary:6>
],
bakers = [
<baker_1 salary:16>
<baker_2 salary:8>
],
candlestick_makers = [
<candlestick_maker_1 salary:25>
<candlestick_maker_2 salary:21>
]
}
Hash has a shift method that returns the first item and removes it from the hash. If the order matters you could perhaps try to sort it reversed when the hash is created.
Just do as below :
def this_example_method
people.each do |job, persons|
persons.tap { |ob| ob.pop(x) }.each do |person|
#do something
end
end
end
Example :
hash = { :a => [1,2,3], :b => [3,5,7] }
hash.each do |k,v|
v.tap(&:pop).each { |i| # working wit i }
end
hash # => {:a=>[1, 2], :b=>[3, 5]}

Recursively convert all numeric strings to integers in a Ruby hash

I have a hash of a random size, which may have values like "100", which I would like to convert to integers. I know I can do this using value.to_i if value.to_i.to_s == value, but I'm not sure how would I do that recursively in my hash, considering that a value can be either a string, or an array (of hashes or of strings), or another hash.
This is a pretty straightforward recursive implementation (though having to handle both arrays and hashes adds a little trickiness).
def fixnumify obj
if obj.respond_to? :to_i
# If we can cast it to a Fixnum, do it.
obj.to_i
elsif obj.is_a? Array
# If it's an Array, use Enumerable#map to recursively call this method
# on each item.
obj.map {|item| fixnumify item }
elsif obj.is_a? Hash
# If it's a Hash, recursively call this method on each value.
obj.merge( obj ) {|k, val| fixnumify val }
else
# If for some reason we run into something else, just return
# it unmodified; alternatively you could throw an exception.
obj
end
end
And, hey, it even works:
hsh = { :a => '1',
:b => '2',
:c => { :d => '3',
:e => [ 4, '5', { :f => '6' } ]
},
:g => 7,
:h => [],
:i => {}
}
fixnumify hsh
# => {:a=>1, :b=>2, :c=>{:d=>3, :e=>[4, 5, {:f=>6}]}, :g=>7, :h=>[], :i=>{}}
This is my helper class. It only converts Strings which are just numbers (Integer or Float).
module Helpers
class Number
class << self
def convert(object)
case object
when String
begin
numeric(object)
rescue StandardError
object
end
when Array
object.map { |i| convert i }
when Hash
object.merge(object) { |_k, v| convert v }
else
object
end
end # convert
private
def numeric(object)
Integer(object)
rescue
Float(object)
end # numeric
end # << self
end # Number
end # Helpers
Helpers::Number.convert [{a: ["1", "22sd"]}, 2, ['1.3', {b: "c"}]]
#=> [{:a=>[1, "22sd"]}, 2, [1.3, {:b=>"c"}]]

How do I convert a Ruby hash so that all of its keys are symbols?

I have a Ruby hash which looks like:
{ "id" => "123", "name" => "test" }
I would like to convert it to:
{ :id => "123", :name => "test" }
hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}
#mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent to_sym, just want to remind that in Ruby 1.8 1.to_sym == nil, so playing with some key types can be misleading):
hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}
s2s =
lambda do |h|
Hash === h ?
Hash[
h.map do |k, v|
[k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]]
end
] : h
end
s2s[hash] #=> {:d=>"e", #<Object:0x100396ee8>=>"g", :a=>{:b=>"c"}}
If you happen to be in Rails then you'll have symbolize_keys:
Return a new hash with all keys converted to symbols, as long as they respond to to_sym.
and symbolize_keys! which does the same but operates in-place. So, if you're in Rails, you could:
hash.symbolize_keys!
If you want to recursively symbolize inner hashes then I think you'd have to do it yourself but with something like this:
def symbolize_keys_deep!(h)
h.keys.each do |k|
ks = k.to_sym
h[ks] = h.delete k
symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
end
end
You might want to play with the kind_of? Hash to match your specific circumstances; using respond_to? :keys might make more sense. And if you want to allow for keys that don't understand to_sym, then:
def symbolize_keys_deep!(h)
h.keys.each do |k|
ks = k.respond_to?(:to_sym) ? k.to_sym : k
h[ks] = h.delete k # Preserve order even when k == ks
symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
end
end
Note that h[ks] = h.delete k doesn't change the content of the Hash when k == ks but it will preserve the order when you're using Ruby 1.9+. You could also use the [(key.to_sym rescue key) || key] approach that Rails uses in their symbolize_keys! but I think that's an abuse of the exception handling system.
The second symbolize_keys_deep! turns this:
{ 'a' => 'b', 'c' => { 'd' => { 'e' => 'f' }, 'g' => 'h' }, ['i'] => 'j' }
into this:
{ :a => 'b', :c => { :d => { :e => 'f' }, :g => 'h' }, ['i'] => 'j' }
You could monkey patch either version of symbolize_keys_deep! into Hash if you really wanted to but I generally stay away from monkey patching unless I have very good reasons to do it.
If you are using Rails >= 4 you can use:
hash.deep_symbolize_keys
hash.deep_symbolize_keys!
or
hash.deep_stringify_keys
hash.deep_stringify_keys!
see http://apidock.com/rails/v4.2.1/Hash/deep_symbolize_keys
Just in case you are parsing JSON, from the JSON docs you can add the option to symbolize the keys upon parsing:
hash = JSON.parse(json_data, symbolize_names: true)
Victor Moroz provided a lovely answer for the simple recursive case, but it won't process hashes that are nested within nested arrays:
hash = { "a" => [{ "b" => "c" }] }
s2s[hash] #=> {:a=>[{"b"=>"c"}]}
If you need to support hashes within arrays within hashes, you'll want something more like this:
def recursive_symbolize_keys(h)
case h
when Hash
Hash[
h.map do |k, v|
[ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ]
end
]
when Enumerable
h.map { |v| recursive_symbolize_keys(v) }
else
h
end
end
Try this:
hash = {"apple" => "banana", "coconut" => "domino"}
# => {"apple"=>"banana", "coconut"=>"domino"}
hash.tap do |h|
h.keys.each { |k| h[k.to_sym] = h.delete(k) }
end
# => {:apple=>"banana", :coconut=>"domino"}
This iterates over the keys, and for each one, it deletes the stringified key and assigns its value to the symbolized key.
If you're using Rails (or just Active Support):
{ "id" => "123", "name" => "test" }.symbolize_keys
Starting with Ruby 2.5 you can use the transform_key method.
So in your case it would be:
h = { "id" => "123", "name" => "test" }
h.transform_keys!(&:to_sym) #=> {:id=>"123", :name=>"test"}
Note: the same methods are also available on Ruby on Rails.
Here's a Ruby one-liner that is faster than the chosen answer:
hash = {"apple" => "banana", "coconut" => "domino"}
#=> {"apple"=>"banana", "coconut"=>"domino"}
hash.inject({}){|h,(k,v)| h[k.intern] = v; h}
#=> {:apple=>"banana", :coconut=>"domino"}
Benchmark results:
n = 100000
Benchmark.bm do |bm|
bm.report { n.times { hash.inject({}){|h,(k,v)| h[k.intern] = v; h} } }
bm.report { n.times { Hash[hash.map{ |k, v| [k.to_sym, v] }] } }
end
# => user system total real
# => 0.100000 0.000000 0.100000 ( 0.107940)
# => 0.120000 0.010000 0.130000 ( 0.137966)
I'm partial to:
irb
ruby-1.9.2-p290 :001 > hash = {"apple" => "banana", "coconut" => "domino"}
{
"apple" => "banana",
"coconut" => "domino"
}
ruby-1.9.2-p290 :002 > hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
{
:apple => "banana",
:coconut => "domino"
}
This works because we're iterating over the hash and building a new one on the fly. It isn't recursive, but you could figure that out from looking at some of the other answers.
hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
You can also extend core Hash ruby class placing a /lib/hash.rb file :
class Hash
def symbolize_keys_deep!
new_hash = {}
keys.each do |k|
ks = k.respond_to?(:to_sym) ? k.to_sym : k
if values_at(k).first.kind_of? Hash or values_at(k).first.kind_of? Array
new_hash[ks] = values_at(k).first.send(:symbolize_keys_deep!)
else
new_hash[ks] = values_at(k).first
end
end
new_hash
end
end
If you want to make sure keys of any hash wrapped into arrays inside your parent hash are symbolized, you need to extend also array class creating a "array.rb" file with that code :
class Array
def symbolize_keys_deep!
new_ar = []
self.each do |value|
new_value = value
if value.is_a? Hash or value.is_a? Array
new_value = value.symbolize_keys_deep!
end
new_ar << new_value
end
new_ar
end
end
This allows to call "symbolize_keys_deep!" on any hash variable like this :
myhash.symbolize_keys_deep!
def symbolize_keys(hash)
new={}
hash.map do |key,value|
if value.is_a?(Hash)
value = symbolize_keys(value)
end
new[key.to_sym]=value
end
return new
end
puts symbolize_keys("c"=>{"a"=>2,"k"=>{"e"=>9}})
#{:c=>{:a=>2, :k=>{:e=>9}}}
Here's my two cents,
my version of symbolize_keys_deep! uses the original symbolize_keys! provided by rails and just makes a simple recursive call to Symbolize sub hashes.
def symbolize_keys_deep!(h)
h.symbolize_keys!
h.each do |k, v|
symbolize_keys_deep!(v) if v.is_a? Hash
end
end
Facets' Hash#rekey is also a worth mentioning.
Sample:
require 'facets/hash/rekey'
{ "id" => "123", "name" => "test" }.deep_rekey
=> {:id=>"123", :name=>"test"}
There is also a recursive version:
require 'facets/hash/deep_rekey'
{ "id" => "123", "name" => {"first" => "John", "last" => "Doe" } }.deep_rekey
=> {:id=>"123", :name=>{:first=>"John", :last=>"Doe"}}
Here's a little recursive function to do a deep symbolization of the keys:
def symbolize_keys(hash)
Hash[hash.map{|k,v| v.is_a?(Hash) ? [k.to_sym, symbolize_keys(v)] : [k.to_sym, v] }]
end

what's the best way to convert a ruby hash to an array

I have a ruby hash that looks like this
{ "stuff_attributes" => {
"1" => {"foo" => "bar", "baz" => "quux"},
"2" => {"foo" => "bar", "baz" => "quux"}
}
}
and I want to turn it into a hash that looks like this
{ "stuff_attributes" => [
{ "foo" => "bar", "baz" => "quux"},
{ "foo" => "bar", "baz" => "quux"}
]
}
I also need to preserve the numerical order of the keys, and there is a variable number of keys. The above is super-simplified, but I've included a real example at the bottom. What's the best way to do this?
P.S
It also needs to be recursive
As far as the recursion goes, here's what we can assume:
1) the key that needs to be manipulated will match /_attributes$/
2) the hash will have many other keys that do not match /_attributes$/
3) the keys inside the hash will always be a number
4) an _attributes hash can be at any level of the hash under any other key
this hash is actually the params hash from a create action in the controller. This is a real example of what will need to be parsed with this routine.
{
"commit"=>"Save",
"tdsheet"=>{
"team_id"=>"43",
"title"=>"",
"performing_org_id"=>"10",
"tdsinitneed_attributes"=>{
"0"=>{
"title"=>"",
"need_date"=>"",
"description"=>"",
"expected_providing_organization_id"=>"41"
},
"1"=>{
"title"=>"",
"need_date"=>"",
"description"=>"",
"expected_providing_organization_id"=>"41"
}
},
"level_two_studycollection_id"=>"27",
"plan_attributes"=>{
"0"=>{
"start_date"=>"", "end_date"=>""
}
},
"dataitem_attributes"=>{
"0"=>{
"title"=>"",
"description"=>"",
"plan_attributes"=>{
"0"=>{
"start_date"=>"",
"end_date"=>""
}
}
},
"1"=>{
"title"=>"",
"description"=>"",
"plan_attributes"=>{
"0"=>{
"start_date"=>"",
"end_date"=>""
}
}
}
}
},
"action"=>"create",
"studycollection_level"=>"",
"controller"=>"tdsheets"
}
Note that this might be long to test if all keys are numbers before converting...
def array_from_hash(h)
return h unless h.is_a? Hash
all_numbers = h.keys.all? { |k| k.to_i.to_s == k }
if all_numbers
h.keys.sort_by{ |k| k.to_i }.map{ |i| array_from_hash(h[i]) }
else
h.each do |k, v|
h[k] = array_from_hash(v)
end
end
end
If we can assume that all the keys are in fact strings which convert cleanly to integers, the following ought to work:
# "hash" here refers to the main hash in your example, since you didn't name it
stuff_hash = hash["stuff"]
hash["stuff"] = stuff_hash.keys.sort_by {|key| key.to_i}.map {|key| stuff_hash[key]}
To take a bit of a liberty, I'm posting a very similar code example to Vincent Robert's.
This one is patches the Hash class with a .to_array method.
class Hash
def to_array(h = self)
return h unless h.is_a? Hash
if h.keys.all? { |k| k.to_i.to_s == k } # all keys are numbers so make an array.
h.keys.sort_by{ |k| k.to_i }.map{ |i| self.to_array(h[i]) }
else
h.each do |k, v|
h[k] = self.to_array(v)
end
end
end
end
It makes usage slightly more convenient.

Resources