A Quick Ruby Recap — I

Muhammad Affan Khan
3 min readMay 10, 2022
Photo by Fotis Fotopoulos on Unsplash

In today's fast-paced software development, one has to work on multiple stacks that include multiple languages and frameworks. Hence forgetting the syntax or function names can be very common but that’s totally fine.

This series would help get the hang of the language with just a few minutes of reading. I am not against reading books at all but since this is a recap, it could save some time.

Running the Ruby Code

If ruby is installed on your machine, or if you’ve already familiar with it you can start practicing. However, if that’s not the case, you can try this online ruby coding experience. Examples discussed here would work directly in the IRB which stands for interactive ruby.

Variables in Ruby

my_var = 10 # valid
my_var2 = 12 # valid
3my_var = 15 # Invalid, can't start with a digit
my var = 20 # Invalid, should be a single word

Constants in Ruby

PI = 3.14159 # A constant in ruby starts with a capital letter
GravitationalConstant = 9.8
# updating the value of a constant would give you a warning:GravitationalConstant = 10(irb): warning: already initialized constant GravitationalConstant

Numbers and Arithmetic Operations in Ruby

#Integers
5 + 3 # 8
7 - 2 # 5
#Floating point
7.0 + 2.0 # 9.0
#Integer and Floating point together
5 + 8.0 # 13.0
8.0 - 4 # 4.0
# Multiplication
6 * 3 # 18 (int to int multiplication would result in integer)
4.0 * 2 # 8.0 (float to int multiplication would result in float)
3 * 3 * 2.0 # 18.0
#Division15/2 # 7, why not 7.5?? This is because Ruby considers a number without decimal point(.) as integer. 15.0/2.0 # 7.5 (float divided by float, results in float)15/2.0 # 7.5 (int divided by float, results in float)
15.0/2 # 7.5 (float divided by int, results in float)

# Exponentials
2 ** 5 # 32
3 ** 3.0 # 27.0 (Did you notice the same rule as above?)

#Modulus
12 % 3 # 0
19 % 5 # 4

Integer and Float Conversion

5.to_f # 5.0
2.5.to_int # 2 Noticed the fractional part being ingnored?

Strings

name = "peter"
name.capitalize! # "Peter"
name.upcase! # "PETER"
#output an string to console
puts "Hi, I am practicing Ruby"
#String concatenation
puts "Hello " + "World" # Hello World
#Also possible with variables
var first = "Good "
var second = "Morning"
puts first + second # "Good Morning"
# String Length
puts "Super Cool Product".length # 18

String Interpolation

name = "Lucy"
message = "Greetings #{name}!"
puts message # Greetings Lucy!
#Multiple string interpolation
a = 1
b = 2
puts "#{a} is less than #{b}"

Conclusion

Enough for today? Let’s summarize what we learned today:

  • Variables
  • Constants
  • Numbers
  • Arithmetics
  • Numeric Conversions b/w integer and float
  • Strings and String interpolation

--

--

Muhammad Affan Khan

Software Engineer | Ruby on Rails | Flutter | Open source lover