If you define a method in a class, that method becomes an instance method. Instance methods are methods that you can call on an instance of that class. (Example)
class User
def emotion
"Happy!"
end
end
user = User.new
user.emotion
result
"Happy!"
Within a class, you can use instance variables (variables shared within the same instance). Variable names start with @. (Example)
class User
def initialize(emotion)
@emotion = emotion
end
def happy
"I am #{@emotion}."
end
end
user = User.new('Happy')
user.happy
result
"I am Happy."
A variable created within a method or block. Start with a lowercase letter, an underscore. Local variables must always be created by assigning a value with = before referencing.
(Example)
class User
def initialize(emotion)
@emotion = emotion
end
def happy
shuffled_emotion = @emotion.chars.shuffle.join
"I am #{shuffled_emotion}."
end
end
user = User.new('Happy')
user.happy
In this example, the local variable would be shuffled_emotion.
result
"I am ayppH."
Introduction to Ruby for those who want to become professionals