Variables

Constant

OPENING_HOURS = "Monday - Friday: 08:00 - 18:00"  #convention
Opening_hours = "Monday - Friday: 08:00 - 18:00"
OpeningHours = "Monday - Friday: 08:00 - 18:00"
Openinghours = "Monday - Friday: 08:00 - 18:00"
OPENINGHOURS = "Monday - Friday: 08:00 - 18:00"

Use SCREAMING_SNAKE_CASE for other constants. [link]

Local variable

local_variable = 123 #convention
_Local_variable = 123
_local_variable = 123

Global variable

$a_global_variable = 123

Instance variable

@a_instance_variable = 123

Initialize a instance variable:

class AnyClass
  attr_reader :color
  def initialize
    @color = 'red'
  end
end

apple = AnyClass.new
apple.color
#=> 'red'

The following is not working:

class AnyClass
  attr_reader :color
  @color = 'red'
  def initialize
    ...
  end
end

apple = AnyClass.new
apple.color
#=> nil

Class variable

@@a_class_variable = 123

class AnyClass
 @class_instance_variable = "none"
 def self.test
   @class_instance_variable = "test"
 end
end
# environment/development.rb
# default setting in development will make the class reload
# so the information in class variables will lost after class reloaded
# enable the cache_classes or giving the default value again
config.cache_classes = false

Reference

results matching ""

    No results matching ""