I am writing integration tests for rails and I want to compare the object created with the JSON object sent. The object returned is not exactly the same as the one sent, (i.e.) it has keys that the object sent doesn't have because I am using active model serializers to pull associations in the returned object. Basically, I just want to compare all the same keys between both objects to see if its the same. Let me know if there is a clean efficient code snippet that does this for me!
TL;DR
"Clever" test code is rarely useful. Each test should be as simple as possible, and it should be testing the behavior of some object rather than its composition. There are always ways to be clever, though.
Using Array Intersection
One unreadably-clever way to do this is to use Array#& to find the intersection of the keys, and then look for equality between the values. This will work on a relatively flat hash. For example:
hash1 = {:key1=>"value1", :key2=>"value2", :key3=>"value3", :key4=>"value4"}
hash2 = {:key1=>"value1", :key2=>"value2", :key5=>"value5"}
Array(hash1.keys & hash2.keys).map { |k| hash1[k] == hash2[k] }.uniq
#=> [true]
If you're using RSpec to test, you could say something like:
it 'has some matching key/value pairs' do
# ... populate hash1
# ... populate hash2
Array(hash1.keys & hash2.keys).
map { |k| hash1[k] == hash2[k] }.uniq.should == [true]
end
Of course, if the expectation is false, then you won't really know why, or which key/value pair was wrong. This is just one of the many reasons that you should always use fixed inputs and outputs for testing, rather than trying to do dynamic comparisons.
You could use Hash#slice, which is an Active Support core extension.
For example, if the keys you want to check are :a, :b, :c, but the result contains :a, :b, :c, :d, slice will reduce the result to just contain the keys you care about:
expected = { :a => 1, :b => 2, :c => 3 }
result = { :a => 1, :b => 2, :c => 3, :d => 4 }
result.slice(:a, :b, :c) == expected
# => true
If you get a NoMethodError: undefined method 'slice' exception, you need to require active_support/core_ext/hash/slice
First, find the keys that both hashes contain, and then compare the value for those keys:
hash1 = {:key1 => "value1", :key2 => "value2", :key3 => "value3", :key4 => "value4"}
hash2 = {:key1 => "value1", :key2 => "value2", :key5 => "value5"}
hash1_keys = hash1.keys
hash2_keys = hash2.keys
comparable_keys = hash1_keys.select{|key| hash2_keys.include?(key)}
comparable_keys.each do |key|
hash1[key].should == hash2[key]
end
Related
deep_symbolize_keys! converts string keys to symbol keys. This works for hashes and all sub-hashes. However, I have a data like this:
arr = [
{'name': 'pratha', 'email': 'p#g.com', 'sub': { 'id': 1 } },
{'name': 'john', 'email': 'c#d.com', 'sub': { 'id': 2 } }
]
arr.deep_symbolize_keys! # this is not working for array of hashes.
In this case, hashes are in an array. So how can i symbolize all at once?
Using Ruby 2.6.3
I also read somewhere that this is deprecated (probably on one of the Rails forum). Is that true? If so, what is the best way to convert keys to symbols in my case?
Currently using this:
def process(emails)
blacklist = ["a", "john", "c"]
e = emails.map do |hash|
blacklist.include?(hash['name']) ? nil : hash.deep_symbolize_keys!
end
e
end
Do you need a copy or an in-place transformation? In-place you can use arr.each(&:deep_symbolize_keys!). For a copy you should use arr.map(&:deep_symbolize_keys). Remember that map does not mutate but returns a new array.
The implementation already handles nested arrays, it just doesn't define the method on Array. So, nest it in a temporary hash and symbolize that. This works for arbitrary types:
[1] pry(main)> def deep_symbolize_keys(object) = {object:}.deep_symbolize_keys[:object];
[2] pry(main)> deep_symbolize_keys([{"a" => 1}, {"b" => {"c" => 2}}])
=> [{:a=>1}, {:b=>{:c=>2}}]
Also, be careful with your key syntax. In your example, your keys are already symbols - they're just quoted symbols:
[3] pry(main)> {a: 1}.keys.first.class
=> Symbol
[4] pry(main)> {'a': 1}.keys.first.class
=> Symbol
[5] pry(main)> {'a' => 1}.keys.first.class
=> String
The syntax is necessary to handle cases like {'a-b': 1}[:'a-b'], but it's very often misleading since they look so much like string keys. I recommend avoiding it entirely unless absolutely necessary - stick to {a: 1} for symbol keys and {'a' => 1} for string keys.
I am looking for the Ruby/Rails way to approach the classic "select items from a set based on matches with another set" task.
Set one is a simple hash, like this:
fruits = {:apples => "red", :oranges => "orange", :mangoes => "yellow", :limes => "green"}
Set two is an array, like this:
breakfast_fruits = [:apples, :oranges]
The desired outcome is a hash containing the fruits that are listed in Breakfast_fruits:
menu = {:apples => "red", :oranges => "orange"}
I've got a basic nested loop going, but am stuck on basic comparison syntax:
menu = {}
breakfast_fruits.each do |brekky|
fruits.each do |fruit|
//if fruit has the same key as brekky put it in menu
end
end
I'd also love to know if there is a better way to do this in Ruby than nested iterators.
You can use Hash#keep_if:
fruits.keep_if { |key| breakfast_fruits.include? key }
# => {:apples=>"red", :oranges=>"orange"}
This will modify fruits itself. If you don't want that, a little modification of your code works:
menu = {}
breakfast_fruits.each do |brekky|
menu[brekky] = fruits[brekky] if breakfast_fruits.include? brekky
end
ActiveSupport (which comes with Rails) adds Hash#slice:
slice(*keys)
Slice a hash to include only the given keys. Returns a hash containing the given keys.
So you can say things like:
h = { :a => 'a', :b => 'b', :c => 'c' }.slice(:a, :c, :d)
# { :a => 'a', :c => 'c' }
In your case, you'd splat the array:
menu = fruits.slice(*breakfast_fruits)
I am using Ruby on Rails 3.2.13 and I would like to remove hash keys which corresponding hash value is blank. That is, if I have the following hash
{ :a => 0, :b => 1, :c => true, :d => "", :e => " ", :f => nil }
then the resulting hash should be (note: 0 and true are not considered blank)
{ :a => 0, :b => 1, :c => true }
How can I make that?
If using Rails you can try
hash.delete_if { |key, value| value.blank? }
or in case of just Ruby
hash.delete_if { |key, value| value.to_s.strip == '' }
There are a number of ways to accomplish this common task
reject
This is the one I use most often for cleaning up hashes as its short, clean, and flexible enough to support any conditional and doesn't mutate the original object. Here is a good article on the benefits of immutability in ruby.
hash.reject {|_,v| v.blank?}
Note: The underscore in the above example is used to indicate that we want to unpack the tuple passed to the proc, but we aren't using the first value (key).
reject!
However, if you want to mutate the original object:
hash.reject! {|_,v| v.blank?}
select
Conversely, you use select which will only return the values that return true when evaluated
hash.select {|_,v| v.present? }
select!
...and the mutating version
hash.select {|_,v| v.present? }
compact
Lastly, when you only need to remove keys that have nil values...
hash.compact
compact!
You have picked up the pattern by now, but this is the version that modifies the original hash!
hash.compact!
With respect to techvineet's solution, note the following when value == [].
[].blank? => true
[].to_s.strip == '' => false
[].to_s.strip.empty? => false
What I'm aiming to do is to create an object which is initialized with a hash and then query this object in order to get values from that hash.
To make things clearer here's a rough example of what I mean:
class HashHolder
def initialize(hash)
#hash = hash
end
def get_value(*args)
# What are my possibilities here?
end
end
holder = HashHolder.new({:a => { :b => { :c => "value" } } } )
holder.get_value(:a, :b, :c) # should return "value"
I know I can perform iteration on the arguments list as in:
def get_value(*args)
value = #hash
args.each do |k|
value = value[k]
end
return value
end
But if I plan to use this method a lot this is going to degrade my performance dramatically when all I want to do is to access a hash value.
Any suggestions on that?
To update the answer since it's been a while since it was asked.
(tested in ruby 2.3.1)
You have a hash like this:
my_hash = {:a => { :b => { :c => "value" } } }
The question asked:
my_hash.get_value(:a, :b, :c) # should return "value"
Answer: Use 'dig' instead of get_value, like so:
my_hash.dig(:a,:b,:c) # returns "value"
Since the title of the question is misleading (it should be something like: how to get a value inside a nested hash with an array of keys), here is an answer to the question actually asked:
Getting ruby hash values by an array of keys
Preparation:
my_hash = {:a => 1, :b => 3, :d => 6}
my_array = [:a,:d]
Answer:
my_hash.values_at(*my_array) #returns [1,6]
def get_value(*args)
args.inject(#hash, &:fetch)
end
In case you want to avoid iteration at lookup (which I do not feel necessary), then you need to flatten the hash to be stored:
class HashHolder
def initialize(hash)
while hash.values.any?{|v| v.kind_of?(Hash)}
hash.to_a.each{|k, v| if v.kind_of?(Hash); hash.delete(k).each{|kk, vv| hash[[*k, kk]] = vv} end}
end
#hash = hash
end
def get_value(*args)
#hash[args]
end
end
If you know the structure of the hash is always in that format you could just do:
holder[:a][:b][:c]
... returns "value".
I am using Ruby on Rails 3.1.0 and I would like to check if an hash is "completely" included in another hash and return a boolean value.
Say I have those hashes:
hash1 = {
:key1 => 'value1',
:key2 => 'value2',
:key3 => 'value3'
}
hash2 = {
:key1 => 'value1',
:key2 => 'value2',
:key3 => 'value3',
:key4 => 'value4',
:key5 => 'value5',
...
}
I would like to check if the hash1 is included in the hash2 even if in the hash2 there are more values than hash1 (in the above case the response that I am looking for should be true)? Is it possible to do that by using "one only code line"\"a Ruby method"?
That will be enough
(hash1.to_a - hash2.to_a).empty?
The easiest way I can think of would be:
hash2.values_at(*hash1.keys) == hash1.values
the more elegant way is to check the equality when one hash merge another.
e.g. rewrite Hash include? instance method for this.
class Hash
def include?(other)
self.merge(other) == self
end
end
{:a => 1, :b => 2, :c => 3}.include? :a => 1, :b => 2 # => true
There is a way:
hash_2 >= hash_1
Alternatively:
hash_1 <= hash_2
More info in this post: https://olivierlacan.com/posts/proposal-for-a-better-ruby-hash-include/
The most efficient and elegant solution I've found - with no intermediary arrays, or redundant loops.
class Hash
alias_method :include_key?, :include?
def include?(other)
return include_key?(other) unless other.is_a?(Hash)
other.all? do |key, value|
self[key] == value
end
end
end
Since Ruby 2.3 you can use built-in Hash#<= method.
Since Ruby 2.3, you can do this:
hash1 <= hash2
I am not sure if I understand the inclusion idea in hash.
To see if it has the same keys(usual problem).
All keys in hash1 are included in hash2:
hash1.keys - hash2.keys == []
Then if you want to compare those values do as suggested in the previous post:
hash1.values - hash2.values_at(*hash1.keys) == []