Dan Karlin
Dan Karlin

Reputation: 17

Setting Attributes using Hash in RUby

I'm currently completely stuck on a school problem and figured I'd reach out for some guidance.

Define a class named User. Its initialize method should take a Hash as an argument. We'll name the argument config and set a default value for the argument to an empty Hash:

class User
  def initialize(config = {})
  end
end

This config = {} the syntax supplies a "default argument" for initialize. If someone initializes a User instance without a config argument, the config variable in the method will automatically be set to the default we gave it--an empty Hash.

The config argument should be used to set any of the following attributes on a user: name, email, bio, age, and sex. If an attribute is not provided in the Hash argument, the initialize method should default it to a value to "n/a". For example:

class User
  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    ...
  end
end

Setting default values is a very common task in Ruby. A basic way to do this is by using the || assignment operator, which means "or". Consider the following examples:

a = 3
a = a || 6
a #=> 3
b = b || 9
b #=> 9

Decode the logic in the conditional assignments above.

We'll also need to access the instance variables set in our initialize method. To do this, we can use the attr_accessor method declaration. The attr_accessor method also lets us declare multiple attributes on one line. For example:

class User
  attr_accessor :name, :email

  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    # ...
  end
end

Finish writing the User class and initialize method to handle all of the required attributes.

I am entirely lost at this point. Thanks in advance.

Upvotes: 0

Views: 3264

Answers (1)

Kathryn
Kathryn

Reputation: 1607

It looks as if you've copied your assignment directly. I'm not going to do the work for you, but I will give you some hints on a few lines of code:

def initialize(config = {})

This is using a default parameter value while defining the method. If the user doesn't provide a config hash, the method will use an empty hash by default.

@name = config[:name] || "n/a"

This statement is using || for flow control. If config[:name] is set, the value is assigned to @name. Otherwise, it defaults to "n/a".

attr_accessor :name, :email

This is a shortcut to create getters and setters for :name and :email. It looks like your assignment is to add bio, age, and sex as instance variables and set them up with appropriate defaults.

Upvotes: 1

Related Questions