Hash delete_if in Ruby [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to remove key-value pairs from a hash whose value is less than the highest key-value pair's value in the hash. Example: If my hash is {:Jan => 3, :Feb =>4, :Mar =>4}, I'd want to remove the :Jan => 3 entry. I am attempting delete_if with a comparison to no avail.
def highestvalue(myhash)
myhash.delete_if { |k,v| v < v}
print myhash
end
months = {:Jan => 3, :Feb =>4, :Mar =>4}
highestvalue(months)

def highestvalue(myhash)
max = myhash.values.max
myhash.delete_if { |k, v| v < max }
end

Related

Instance of a number in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I know "instance_of?" searches for an instance of a class. I am looking for an object that can find an instance of the user input inside the array. Code for clarity:
user_input = nil
array = [[1, 2, 3][4, 5, 6][7, 8, 9]]
until user_input.instance_of?(array) do
print "Choose a number in our array"
begin
user_input = gets.chomp
rescue ArgumentError
user_input = nil
puts "Not in our array. Try again!"
end
end
You can use Array#include?
Here's a simple implementation. I simplified the array for example purposes.
array = [1, 2, 3, 4, 5, 6]
puts "Enter a number"
while user_input = gets.chomp
if array.include?(user_input.to_i)
puts "You got it."
break
else
puts "Not in our array. Try again!"
end
end

How can I filter an array of objects based on a hash of conditions in Ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to pass hash:
filter_search = {age: 20, weight: 30, height: 30, salary: (100000..200000)}
to method
def search(array, filter)
array.select do |elem|
???????
end
end
filtered_array = search(some_array, filter_search)
How can I do this? Maybe I'm thinking in wrong way and there is another pattern to solve this?
Assuming the array parameter an array of objects that have the appropriate methods (age, weight, height, salary) and you want to return a filtered array of the ones that perfectly match your hash filter, something like this might work.
def search(array, filter)
array.select do |elem|
filter.all? do |key, value|
elem.send(key) == value
end
end
end
If you have hashes in your array instead of objects, you would use:
def search(array, filter)
array.select do |elem|
filter.all? do |key, value|
elem[key] == value
end
end
end

Assigning hash inside each does not work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This:
(0..8).each do |n|
"a_#{n}" = {}
end
gives me an error "syntax error, unexpected '=', expecting keyword_end". I wanted to create a_0 = {}, a_1 = {}, a_2 = {} etc.
I think you want an array of hashes.
a = []
(0..8).each do |n|
a[n] = {}
end
Result:
a #=> [{}, {}, {}, {}, {}, {}, {}, {}, {}]
a[0] #=> {}
a[1] #=> {}
...etc...
although depending on what you need to do next, this type of initialization may not be necessary.
binding.instance_eval do (0..8).each do |i|
local_variable_set("a_#{i}", {})
...
end end
Without bad magic, you won't get the functionality you want (there are ways to do that but they are bad and hacky). Use a hash or array instead.

Iterating over values for array of hashes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have array of hashes like:
AWARD = [
{'KARMA_POINTS' => %w(initiate apprentice knight ace guardian sage master grand_master)},
{'MICROBLOGS_POSTED' => %w(uno_plus)},
{'COMMENTS_POSTED' => %w(first_responder)},
{'IDEAS_POSTED' => %w(aryabhatta newton einstein)}
]
Need to iterate over values for a key if it matches a particular key in given hash (AWARD).
Any suggestion and solution will be appreciated.
Is this what you want :
AWARD.each do |hash|
# I used Hash#[] method. This method will return key if found, or nil.
# As `nil` treated as falsy in Ruby, on nil **unless** block wouldn't be executed,
# otherwise it will.
unless hash['match_key'].nil?
# I am calling here `Hash#each` method.
hash.each do |key,value|
value.each do |elem| # as values are Array, so calling Array#each
# your code
end
end
end
end
Iterate over each Hash in the array. For each Hash, iterate over each key=>value pair. For each key=>value pair, do your thing.
AWARD = [
{'KARMA_POINTS' => %w(initiate apprentice knight ace guardian sage master grand_master)},
{'MICROBLOGS_POSTED' => %w(uno_plus)},
{'COMMENTS_POSTED' => %w(first_responder)},
{'IDEAS_POSTED' => %w(aryabhatta newton einstein)}
]
AWARD.each do |hash|
hash.each do |key,value|
value.each do |item|
# your code here
puts item
end
end
end

Retrieve nested hash values ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a nested Hash like this :
{
:a=>{
:toto=>{
:foo=>10,
:bar=>11,
:baz=>12
},
:titi=>"a"
},
:b=>{
:toto=>{
:foo=>31,
:bar=>45,
:baz=>78
},
:titi=>"b"
}
}
My goal is to sum all the :baz values. I'm sure there is a beautiful way to do this in ruby. Any idea?
Thanks.
#inject is very powerful method that works for both arrays and hashes. You can walk through values of hash and sum the needed key to the total sum.
hash.inject(0) { |sum, (_,v)| sum += v[:toto][:baz] } # => 90
h = {
:a=>{
:toto=>{
:foo=>10,
:bar=>11,
:baz=>12
},
:titi=>"a"
},
:b=>{
:toto=>{
:foo=>31,
:bar=>45,
:baz=>78
},
:titi=>"b"
}
}
h.inject(0){|sum,(_,v)| sum +=v.fetch(:toto,{}).fetch(:baz,0)}
This method finds all :baz elements, regardless of their path.
h = {
:a=>{
:toto=>{
:foo=>10,
:bar=>11,
:baz=>12,
},
:titi=>"a"
},
:b=>{
:toto=>{
:foo=>31,
:bar=>45,
:baz=>78,
},
:titi=>"b",
},
}
def sum_baz(hash)
hash.values.reduce(0) do |memo, elem|
if elem.is_a?(Hash)
memo += sum_baz(elem)
memo += elem[:baz] if elem[:baz]
end
memo
end
end
sum_baz(h) # => 90

Resources