Explain how you define Instance Variable, Global Variable and Class Variable in Ruby?
Explain how you define Instance Variable, Global Variable and Class Variable in Ruby?
Sure, I'd be happy to help you with that Ruby on Rails interview question. Here's an explanation of instance variables, global variables, and class variables in Ruby:
Instance variables in Ruby are variables that are specific to an object or instance of a class. They are prefixed with the "@" symbol and can only be accessed within the instance methods of the class. Instance variables are used to store data that is unique to each object.
Example:
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, my name is #{@name}."
end
end
person1 = Person.new("Alice")
person1.greet # Output: Hello, my name is Alice.
Global variables in Ruby are variables that can be accessed from anywhere in the program, including outside of classes. They are prefixed with the "$" symbol. Global variables should be used sparingly as they can lead to naming conflicts and make the code harder to maintain.
Example:
$greeting = "Hello, world!"
def say_greeting
puts $greeting
end
say_greeting # Output: Hello, world!
``...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào