Câu hỏi phỏng vấn Ruby on Rails
Câu hỏi

Explain how you define Instance Variable, Global Variable and Class Variable in Ruby?

Câu trả lời

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

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:

ruby Copy
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

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:

ruby Copy
$greeting = "Hello, world!"

def say_greeting
  puts $greeting
end

say_greeting  # Output: Hello, world!
``...
junior

junior

Gợi ý câu hỏi phỏng vấn

expert

How To Use Two Databases Into A Single Application?

senior

What is the difference between string and text in Rails?

junior

What Are The Various Components Of Rail?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào