Testing if a hash has any of a number of keys
No need to loop:
(hash.keys & keys).any? # => true
Explanation:
.keys
returns all keys in a hash as an array. &
intersects two arrays, returning any objects that exists in both arrays. Finally, .any?
checks if the array intersect has any values.
Determine if hash contains any key from a set of keys?
Consider Enumerable.any?
[:a, :b, :e].any? {|k| h.key?(k)}
From IRB:
>> h = {:a => 1}; [:x].any? {|k| h.key?(k)}
=> false
>> h = {:a => 1}; [:x, :a].any? {|k| h.key?(k)}
=> true
Happy coding.
Check if a hash's keys include all of a set of keys
%i[a b c d].all? {|s| hash.key? s}
How to check if a specific key is present in a hash or not?
Hash
's key?
method tells you whether a given key is present or not.
session.key?("user")
How do you check for matching keys in a ruby hash?
I think you could replace those for
loops with the Array#each
. But in your case, as you're creating a hash with the values in people_list
, then you could use the Enumerable#each_with_object
assigning a new Hash as its object argument, this way you have your own person
hash from the people_list
and also a new "empty" hash to start filling as you need.
To check if your inner hash has a key with the value person[:favourites][:tv_show]
you can check for its value just as a boolean one, the comparison with false can be skipped, the value will be evaluated as false or true by your if statement.
You can create the variables tv_show
and name
to reduce a little bit the code, and then over your tv_friends
hash to select among its values the one that has a length greater than 1. As this will give you an array inside an array you can get from this the first element with first
(or [0]
).
def tv_show(people_list)
tv_friends = people_list.each_with_object(Hash.new({})) do |person, hash|
tv_show = person[:favourites][:tv_show]
name = person[:name]
hash.key?(tv_show) ? hash[tv_show] << name : hash[tv_show] = [name]
end
tv_friends.values.select { |value| value.length > 1 }.first
end
Also you can omit parentheses when the method call doesn't have arguments.
Check if a string includes any of the keys in a hash and return the value of the key it contains
I find this way readable:
hash_key_in_s = s[Regexp.union(h.keys)]
p h[hash_key_in_s] #=> "v1"
Or in one line:
p h.fetch s[Regexp.union(h.keys)] #=> "v1"
And here is a version not using regexp:
p h.fetch( h.keys.find{|key|s[key]} ) #=> "v1"
How to test with Rspec that a key exists inside a hash that contains an array of hashes
RSpec allows you to use the have_key predicate matcher to validate the presence of a key via has_key?
, like so:
subject { described_class.order_items_by_revenue }
it "includes revenue key" do
expect(subject.first).to have_key(:revenue)
end
RSpec: How to test existence of keys in an array of hashes?
This will help:
describe "your test description" do
let(:hash_keys) { [:one, :two].sort } # and so on
subject(:array) { some_method_to_fetch_your_array }
specify do
expect(array.count).to eq 50
array.each do |hash|
# if you want to ensure only required keys exist
expect(hash.keys).to contain_exactly(*hash_keys)
# OR if keys are sortable
# expect(hash.keys.sort).to eq(hash_keys)
# if you want to ensure that at least the required keys exist
expect(hash).to include(*hash_keys)
end
end
end
One problem with that approach: if the test fails, you'll have trouble finding out exactly which array index caused the failure. Adding a custom error message will help. Something like the following:
array.each_with_index do |hash, i|
expect(hash.keys).to contain_exactly(*hash_keys), "Failed at index #{i}"
end
Test that hash contains specific keys and that values for those keys are not nil
something like this:
test_method.values_at("key1", "key2").should_not include(nil)
Using new Ruby pattern matching to check if a hash has certain keys
You're looking for the =>
operator:
h = {name: "John", salary: 12000, email: "john@email.com" }
h => {name: String, salary: Numeric, email: String} # => nil
With an additional pair (test: 0
):
h[:test] = 0
h => {name: String, salary: Numeric, email: String} # => nil
Without the :name
key:
h.delete :name
h => {name: String, salary: Numeric, email: String} # key not found: :name (NoMatchingPatternKeyError)
With the :name
key but the class of its value shouldn't match:
h[:name] = 1
h => {name: String, salary: Numeric, email: String} # String === 1 does not return true (NoMatchingPatternKeyError)
A strict match:
h[:name] = "John"
h => {name: String, salary: Numeric, email: String} # => rest of {:test=>0} is not empty
The in
operator returns a boolean value instead of raising an exception:
h = {name: "John", salary: 12000, email: "john@email.com" }
h in {name: String, salary: Numeric, email: String} # => true
h[:name] = 1
h in {name: String, salary: Numeric, email: String} # => false
Related Topics
How to Express Infinity in Ruby
How to Create an Anchor and Redirect to This Specific Anchor in Ruby on Rails
How to Create a Hash in Ruby That Compares Strings, Ignoring Case
Ruby: Intersection Between Two Ranges
An Algorithm for Converting a Base-10 Number to a Base-N Number
New Rails Project: 'Bundle Install' Can't Install Rails in Gemfile
What Are <-- Ruby Strings Called? and How to Insert Variables in Them
How to Install Ruby 2.0.0 Correctly on Ubuntu 12.04
How to Click First Link in List of Items After Upgrading to Capybara 2.0
How to Test Exception Raising in Rails/Rspec
How to Generate Links with Trailing Slash in Rails 3
Which Ruby Version am I Really Running
Rails Date Format in Form Field
Heroku App Crash H10 - Bash: Bin/Rails: No Such File or Directory
Error: While Executing Gem ... (Zlib::Gzipfile::Error) Not in Gzip Format
Decrypting Salted Aes File Generated on Command Line with Ruby