Last active
June 23, 2021 06:38
-
-
Save JuzerShakir/15a8decf99f579a9a83266a1c8384d4c to your computer and use it in GitHub Desktop.
Constants & Variable in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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