I thought I’d write some note on my month of Ruby. Mainly to cement my learning. I find writing things down helps my process. I’ll keep adding to post as and when I want to make a note of something I find interesting.
Comments:
# single line of comments (I'll use this to
show console output)
=begin
lots of
lines of
comments
between these
markers
=end
Variables:
You set a variable by giving it a name eg. country, first_name, last_name. Convention is to keep them lowercase with underscore between words.
first_name = "John"
last_name = "Smith"
age = 65
adult = true
How to capitalise:
first_name = "john"
first_name.capitilize # John
How to uppercase or lowercase:
first_name.upcase # JOHN
first_name.downcase # John
Reverse & length:
first_name.reverse # nhoj
first_name.length # 4
Printing to the console:
print first_name.upcase # JOHN
print and puts do two different things, prints adds everything in line in the console. Puts shows things on each line.
print first_name.upcase
print last_name.upcase
# JOHNSMITH
puts first_name.upcase
puts last_name.upcase
# JOHN
# SMITH
How to add a variable in to a string:
puts "My name is #{first_name}."
# My name is John.
Maths:
All the classic maths operators.
Addition (+
)
Subtraction (-
)
Multiplication (*
)
Division (/
)
Exponentiation (**
)
Modulo ({151bccf5f64c347946bc19dad4e6e94d96340062ed0c390499aa4e37c867c926}
)
var = 4 + 4
print var # 8
var = 5 - 1
print var # 4
var = 3 * 3
print var # 9
var = 6/2
print var # 3
var = 2**3
print var # 8 ( 2*2*2 )
var = 9 {151bccf5f64c347946bc19dad4e6e94d96340062ed0c390499aa4e37c867c926} 2
print var # 1 ( 2 goes in to 9 four times with 1 remainder )
Comparisons:
and: – && – both have to be true
or: – || – only one has to be true
reverse result: – ! – opposite
( 8 == 8 ) && ( 2 == 2 ) # true
( 3 == 1 ) || ( 4 == 4 ) # true
!( true ) # false
Control flow
If this is true
else if this true
else
end
In the next the code I will write a code to replace the letter “h” with “aitch” in a given string using global substitution. A bit pointless but fun all the same. Often you have to sanitise text coming in to a database to make sure no odd data is entering your system so knowing how to manipulate text is useful.
You can have many else if statements but there is a better way to do this with a case statement.
if first_name.include? "h"
first_name.gsub!(/h/ "aitch")
puts "Hello, #{first_name}!"
else
print "No 'h' in this string"
end
Leave a Reply