Warnings on Ruby


#1

https://www.codecademy.com/courses/learn-ruby/lessons/introduction-to-ruby/exercises/math?action=lesson_resume

Hi team!

I’m currently starting an Introduction to Ruby and when writing the below code keep getting an error message. I know it’s nothing too complex at the moment and it still pulls through the answers but unsure why it keeps happening. Appreciate any help or advice someone can give me!

Thanks,
Ellie



MyNum3 = 67%2
MyNum4 = 52*22
MyNum5 = 798+4832

puts MyNum3
puts MyNum4
puts MyNum5


(ruby):1: warning: already initialized constant Context::MyNum3
(ruby):1: warning: previous definition of MyNum3 was here
1
1144
(ruby):2: warning: already initialized constant Context::MyNum4
5630
(ruby):2: warning: previous definition of MyNum4 was here
(ruby):3: warning: already initialized constant Context::MyNum5
(ruby):3: warning: previous definition of MyNum5 was here


#2

You are initializing a constant. Since it appears Mynum is already defined Ruby squawks at you a bit but runs things anyway.

Variables starting with a capital are constants in Ruby.
For now just calling your variable mynum will work


#3

The approach which Ruby takes towards “constants” is pretty unique
within programming languages. The rules are:

  • Every identifier which starts with an upper case letter is called a
    "constant" in Ruby.

  • The term “constant” does not mean exactly what we are known from every
    day life (a.k.a. mathematics etc.), because you can modify these
    "constants"; however, every modification evokes a warning.

Hence, unless we enjoy it being flooded with warnings, we should not
modify things which are named with an upper case starting letter.

You can use a lower case letter, or prepend your name with an
underscore, depending on your taste.

Ronald


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.