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:

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:

$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

senior

What is ActiveJob ? When should we use it?

junior

Explain what is a class library in Ruby?

junior

List out what can Rails Migration do?

Bình luận

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

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