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.
attr_accessorand add a line for each required attribute following the existing pattern to theinitialize. Or do I miss something? - spickermann