简体   繁体   中英

ruby hash where keys are from an array and value as a default value

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?

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM