DEV Community


Variables in Ruby

Dev. I love dogs, cookies, and learning new things.
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”
Enter fullscreen mode Exit fullscreen mode

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” a good dog! = “Waffles”
Enter fullscreen mode Exit fullscreen mode

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:

Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

rdandekarslb profile image
Rashmin Dandekar

Why is

ifDog_is_waffles = “Good Boy”


mariel profile image
mariel Author

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!