Ruby Monstas


Methods

Methods

Methods have 2 main uses:

  1. Asking an object a question
  2. Changing an object in some way

Today, we're only looking at the asking part

String methods

Try this in IRB!

"I love Ruby".length
=> 11

Note: Length includes spaces!

Note: Return value is an Integer!

Note: Syntax is
object.method

String methods

Try this in IRB!

"I love Ruby".reverse
=> "ybuR evol I"

Note: Return value is another String!

String methods

Try this in IRB!

"Ruby".upcase
=> "RUBY"

String methods

Try this in IRB!

"Ruby".downcase
=> "ruby"

Integer methods

Try this in IRB!

1.odd?
=> true

Integer methods

Try this in IRB!

-5.even?
=> false
Note: Methods that end in
?
return either
true
or
false
. They are yes/no questions!

Method arguments

Some methods require additional information

Try this in IRB!

"I love Ruby".include?("Ruby")
=> true
"I love Ruby".include?("Rails")
=> false
Note: What does
"I love Ruby".include?
do?
Note: To work correctly,
include?
requires extra information
Note: Syntax is
object.method(argument)

Methods are chainable!

Try this in IRB!

"I love Ruby".length.odd?
=> true
Note: We have "chained" the methods
length
and
odd?
Note: Ruby first executes
"I love Ruby".length
, which returns the integer
11
and then it executes the method
odd?
on that which returns the result
true

Documentation

You don't have to know all of these method names by heart!

Googling helps! For example, google for "ruby doc string reverse"

One of the results will be: http://ruby-doc.org/core/String.html. This is the official Ruby documentation. Use Ctrl + F to find things on the website.

Another good source is Stackoverflow

Additional Resources

Ruby For Beginners: Interactive Ruby

What questions do you have?