Reputation: 105
I want to make a method named default_classroom. so that it takes an array of keys and a default value and returns a hash with all keys set to the default value. (Like, all students go to the same classroom. Here, students are the keys and class as a default value)
def default_classroom(students, default_class)
end
puts default_classroom([:jony, :marry], 8)
# should return => {jony: 8, marry: 8}
i did this:
def default_classroom(students, default_class)
Hash[ students, default_class]
end
and also this:
def default_classroom(students, default_class)
Hash[*students.flatten(default_class)]
end
but still not working. Will you please advice me, How can i complete that?
Upvotes: 1
Views: 93
Reputation: 110675
There are many way to do this. Here are three.
#1
def default_classroom(students, default_class)
Hash[ students.product([default_class]) ]
end
students = %w[Billy-Bob, Trixie, Huck]
#=> ["Billy-Bob", "Trixie", "Huck"]
default_class = "Roofing 101"
default_classroom(students, default_class)
#=> {"Billy-Bob"=>"Roofing 101", "Trixie"=>"Roofing 101",
# "Huck"=>"Roofing 101"}
For Ruby versions >= 2.0, you could instead write:
students.product([default_class]).to_h
#2
def default_classroom(students, default_class)
students.each_with_object({}) { |s,h| h[s] = default_class }
end
#3
Depending on your application, you may need only specify the hash's default value (and not add a key-value pair for each student). After reviewing the documentation for Hash#new, you might think this would be done as follows:
h = Hash.new(default_class)
#=> {}
Then:
h["Billy-Bob"] == "Real Analysis"
evaulates to:
"Roofing 101" == "Real Analysis"
#=> false
but the hash remains empty:
h #=> {}
Instead, initialize the hash with a block, like this:
h = Hash.new { |h,k| h[k]=default_class }
#=> {}
Then:
h["Billy-Bob"] == "Real Analysis"
again evaulates to:
"Roofing 101" == "Real Analysis"
#=> false
but now:
h #=> {"Billy-Bob"=>"Roofing 101"}
Upvotes: 3