Skip to content

Instantly share code, notes, and snippets.

@JuzerShakir
Last active June 23, 2021 06:38
Show Gist options
  • Save JuzerShakir/15a8decf99f579a9a83266a1c8384d4c to your computer and use it in GitHub Desktop.
Save JuzerShakir/15a8decf99f579a9a83266a1c8384d4c to your computer and use it in GitHub Desktop.
Constants & Variable in Ruby
# Date Created: 20 June 2021
# Ruby Version 3.0.0p
# initiated constant
FRUIT = 'Apple' # => Apple
# can be modified
FRUIT << 's' # => Apples
# and can also give totally different value, but with a warning raised by ruby
FRUIT = 'Orange' # => warning: already initialized constant FRUIT
# => Orange
# we can freeze strings so that it cant be modified later
FRUIT.freeze
# FRUIT << 's' # => FrozenError, cannot be modified
# but we can change its value with warning massage
FRUIT = 'Banana' # => warning: already initialized constant FRUIT
# => Banana
# classes, modules etc are all constants, hence the first letter is capital
class On_constants
# constants cannot be defined inside the methods
Student = 4
# varaible
student = 0
def const
# calling constant
puts Student
end
def var
#puts student # => NameError, as 'student' var is not founc in this method
end
end
# accessing constant through class
p On_constants::Student # => 4
# constant available to any methods of class
On_constants.new.const # => 4
# accesssing variable student inside a method is not possible
# On_constants.new.var # => # NameError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment