27
loading...
This website collects cookies to deliver better user experience
cd 100_days_of_ruby/
mkdir Day_2 && cd Day_2/ && touch basics.rb
codium .
# Assigning values to variables
apples = 4 # Integer
hello = "Hello" # String
money = 6.5 # Float
is_adult = true # Boolean
int apples = 4
in ruby though you can simply assign any value to any variable that you want.#
, in ruby this is how you create a comment. # I'm a single line comment. Everything we type after the character # is a comment.
=begin
I'm a multi line comment.
We can type anywhere in between =begin and =end
And we can have as many lines as we want!
=end
puts apples.is_a?(Integer)
puts apples.is_a?(String)
ruby basics.rb
. The output should be the following:true
false
apples = 4
so the variable apples
is an Integer. Now we called the method is_a?
to check what type is the variable apples
. Obviously when we say apples.is_a?(Integer)
it returns true since apples
has the value 4 and returns false when we check if it's a String.# Basic math operations
x = 5
y = 12
puts x + y # Addition
puts x - y # Subtraction
puts x * y # Multiplication
puts y / x # Division
puts y % x # Modulo
puts x ** 2 # Exponent
x
and y
are both Integers so when do y / x
then answer will always be an Integer. Sometimes that's not a problem, for example if we had 6 / 3
that would be equal to 2
which is an Integer. But in our case we have 12 / 5
which is equal to ~2.4
.y / x
is 2
which is wrong. To fix that we need to simply make either x
or y
a Float.x = 5.0
y = 12
2.4
as it should be." "
. But there are a lot of things that we can do with Strings, we can manipulate them in a lot of ways.# Fun with Strings
puts "Hello," + " " + "World!" # Concatenating strings
age = 22 # age is an Integer
puts "I'm #{age} years old!" # Interpolating
+
plus symbol for concatenating strings but that's common with many languages.age
and assign it the value 22
. But on the next line we did something weird, we used the #
symbol inside of a string.#{var}
and that will "embed" the value of a variable to a String.puts hello.reverse # print the string in reverse order
puts hello.upcase # print the string with every letter being upercase
puts hello.downcase # print the string with every letter being lowercase
puts hello.length # print the length of the string
puts hello.empty? # check if the string is empty => returns false cause it's not the case
puts "".empty? # check if the string is empty => returns true cause we have an empty string