loading...

Variables in Ruby

mariel profile image mariel Updated on ・1 min read

A couple of brief notes on Ruby variables:

Variables are set with an = sign and can be reassigned at any time. They are named with snake_case instead of CamelCase.

good_dog = “Waffles”

Snake Case is so named because it looks like a winding snake, as_the_words_rise_and_fall_with_the_underscores. Camel Case is named for the “humps” each capital letter creates in the variable name: WafflesIsAGoodBoy.

In Ruby, variables cannot:

  • Start with a number

  • Be a reserved word

  • Have punctuation or spaces

So the below are not valid:

1goodBoy = “Waffles”

if = “Good Boy”

.waffles.is a good dog! = “Waffles”

Variables beginning with uppercase letters are - PLOT TWIST - constants. A constant is a variable that is just that. Its value cannot be changed. If I want to declare my dog, Waffles, to be the best boy in the universe for all time:

BEST_DOG_IN_THE_UNIVERSE = “Waffles”

A note re: interpolation: Interpolation is the act of using a variable as a stand-in inside a string and having Ruby (or the language you are using) evaluate that variable and fill in its value.

For example:

Note that this will only work with double quotes.

Posted on Jan 19 by:

mariel profile

mariel

@mariel

Software engineer! <3 Lawyer! I love dogs, cookies, and learning new things.

Discussion

markdown guide
 

Why is

ifDog_is_waffles = “Good Boy”

invalid?

 

Hi Rashmin, looking back on this, you're right that it's not technically invalid - I think at the time I was trying to illustrate using reserved words in variable names, like "if". To be truly invalid, I'd need to try and assign a reserved word itself (e.g. if = "waffles"), but the example I gave is still a really poor naming choice. I'll make a note to update my post so it's more clear. Thank you!