Instance Variables in ruby

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值