Session 5

String Methods

There are a ton of methods you can call on String objects. Here are a few examples:

# string methods
var1 = 'Hello World.'
 
puts var1
puts var1.reverse!
puts var1.length
puts var1.upcase
puts var1.downcase
puts var1.swapcase
puts var1.capitalize
 
puts var1
 
puts
 
line_width = 50
puts '*' * line_width
puts var1.center(line_width)
puts var1.ljust(line_width)
puts var1.rjust(line_width)
 
# see Google: ruby string

Math Methods

All operators are actually methods. Here are some other math operations:

puts 'exponentiation'
puts 4 ** 2     # four squared
puts 5 ** 0.5   # square root of five
puts
 
puts 'modulus'
# divide by, then return remainder
puts 5 % 2      # 5/2 is 2 remainder 1, so return 1
puts
 
puts 'absolute value'
number = -5
puts number.abs # 5
puts
 
puts 'random numbers'
puts rand       # a pseudorandom number: 0.0 <= rand < 1.0
x = 6
puts rand(x)    # 0 <= x < 6
puts rand(x)+1  # roll a die

There are also methods in the Math module (we'll talk about what a module is later).

puts Math::PI
puts Math::sqrt(4)

Comparisons

You can write "test" expressions that return true or false. These expressions are useful for branching and looping.

# comparisons (true or false?)

puts 'greater than'
puts 1 > 2          # false
puts

puts 'less than'
puts 1 < 2          # true
puts

puts 'greater than or equal to'
puts 5 >= 5         # true
puts

puts 'less than or equal to'
puts 5 <= 4         # false
puts

puts 'equal to'
puts 1 == 1         # true
puts

puts 'not equal to'
puts 1 != 2         # true
puts

puts 'can do it with strings too'
puts 'cat' < 'dog'  # true: 'c' comes before 'd'
puts 'cat' < 'Dog'  # false: 'D' comes before 'c'
puts '2' < '10'     # false: '2' comes after '1'
puts

Flow Control

You'll want your programs to respond differently to different inputs or to do something over and over until a certain condition occurs.

puts 'branching'
name = 'Chris'
puts 'Hello, ' + name + '.'
if name == 'Chris'
  puts name + ' is my name, too!'
end
puts
 
name = 'Fred'
puts 'Hello, ' + name + '.'
if name == 'Chris'
  puts name + ' is my name, too!'
else
  puts 'Nice to meet you, ' + name + '.'
end
puts
 
name = 'Brian'
puts 'Hello, ' + name + '.'
if name == 'Chris'
  puts name + ' is a teacher'
elsif name == 'Brian'
  puts name + ' is a teacher'
else
  puts name + ' is a student'
end
puts
 
name = 'Brian'
puts 'Hello, ' + name + '.'
if name == 'Chris' || name == 'Brian' # Chris OR Brian
  puts name + ' is a teacher'
else
  puts name + ' is a student'
end
puts
 
# looping
puts 'while loop'
 
input = ''
while input != 'quit'
  puts input
  input = gets.chomp
end
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License