Dogs have many shared characteristics, like the abilities to wag their tails and drink water from a bowl, but they also have information about them that is variable,
like their breed or their name.
Similarly, when designing an application, your users will have common traits, like the ability to log in and out, but some information will be variable,
like a username or email address. Let’s start by setting up a new User
class. You can follow along in either irb or by running a script from the command line.
class User # stuff will go here end
By the end of this lesson, you’ll be able to define a User
class that can track its own user information.
Say you wanted to assign a user’s username. You might try something like this.
julia = User.new julia.username = "coolgirl2000" # NoMethodError: undefined method `username' for #<User:0x007fc6fa034148>
Let’s pause to take a look at that error bit by bit.
NoMethodError
: If I had to guess, I’d say this likely has something to do with a method not existing.undefined method 'username'
: Suspicions confirmed. It looks like our code can’t find a 'username' method. That makes sense, we never defined one.
But you weren't trying to create a new method! You were thinking about this username
like a variable, right?
Ruby has no way of distinguishing between variables and methods in this case, since they both come after the .
, so it only supports instance methods.