Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a default value with hashes in ruby

Tags:

ruby

I am trying to get a default value whilst using hashes in ruby. Looking up the documentation you use a fetch method. So if a hash is not entered then it defaults to a value. This is my code.

def input_students
  puts "Please enter the names and hobbies of the students plus country of    birth"
  puts "To finish, just hit return three times"

  #create the empty array
  students = []
  hobbies = []
  country = []
  cohort = []

  # Get the first name
  name = gets.chomp
  hobbies = gets.chomp
  country = gets.chomp
  cohort = gets.chomp

  while !name.empty? && !hobbies.empty? && !country.empty? && cohort.fetch(:cohort, january) do #This is to do with entering twice
    students << {name: name, hobbies: hobbies, country: country, cohort: cohort} #import part of the code.
    puts "Now we have #{students.count} students"

    # get another name from the user
    name = gets.chomp
    hobbies = gets.chomp
    country = gets.chomp
    cohort = gets.chomp
  end
  students
end
like image 819
AltBrian Avatar asked Sep 17 '16 16:09

AltBrian


1 Answers

You have several options. @dinjas mentions one, likely the one you want to use. Suppose your hash is

h = { :a=>1 }

Then

h[:a] #=> 1
h[:b] #=> nil

Let's say the default is 4. Then as dinjas suggests, you can write

h.fetch(:a, 4) #=> 1
h.fetch(:b, 4) #=> 4

But other options are

h.fetch(:a) rescue 4 #=> 1
h.fetch(:b) rescue 4 #=> 4

or

h[:a] || 4 #=> 1
h[:b] || 4 #=> 4

You could also build the default into the hash itself, by using Hash#default=:

h.default = 4
h[:a] #=> 1
h[:b] #=> 4

or by defining the hash like so:

g = Hash.new(4).merge(h)
g[:a] #=> 1
g[:b] #=> 4

See Hash::new.

like image 155
Cary Swoveland Avatar answered Oct 22 '22 00:10

Cary Swoveland