Custom methods
# Methods
def say_hello(thing_to_say)
puts thing_to_say
end
say_hello 'Good afternoon!1'
say_hello('Good afternoon!2')
# Methods
def multiply(first_num, second_num)
first_num.to_f * second_num.to_f # The last evaluated statement is what the method is going to return
end
puts multiply(10,5) # In order to use the method (function), it needs to be defined first
Splat arguments are arguments preceded by a *
, which tells the program that the method can receive one or more arguments.
def what_up(greeting, *friends)
friends.each { |friend| puts "#{greeting}, #{friend}!" }
end
what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")
Source: https://www.codecademy.com/courses/learn-ruby/lessons/methods-blocks-sorting/exercises/splat
Default parameters
def alphabetize(arr, rev=false)
...
end
What this does is tell Ruby that alphabetize
has a second parameter, rev
(for “reverse”) that will default to false
if the user doesn’t type in two arguments. You might have noticed that our first call to alphabetize
in exercise 1 was just
alphabetize(books)
Ruby didn’t see a rev
, so it gave it the default value of false
.
We can use something like parameter = false
in the declaration of our method to expect an argument
and assigning a false
value if that argument is not provided, for example.
def alphabetize(arr, rev=false)
if rev
arr.sort { |item1, item2| item2 <=> item1 }
else
arr.sort { |item1, item2| item1 <=> item2 }
end
end
books = ["Heart of Darkness", "Code Complete", "The Lorax", "The Prophet", "Absalom, Absalom!"]
puts "A-Z: #{alphabetize(books)}"
puts "Z-A: #{alphabetize(books, true)}"
Built in methods
Everything in Ruby is an object (even an integer), so we can use methods on anything.
.class
irb(main):001:0> first = "Damian"
=> "Damian"
irb(main):002:0> last = "Demasi"
=> "Demasi"
irb(main):003:0> full = "#{first} #{last}"
=> "Damian Demasi"
irb(main):004:0> full.class
=> String
irb(main):005:0> full.class
=> String
irb(main):006:0> "Damian".class
=> String
irb(main):008:0> 99.class
=> Integer
irb(main):009:0> 99.9.class
=> Float
.to_s
and .to_i
irb(main):011:0> 10.class
=> Integer
irb(main):012:0> 10.to_s
=> "10"
irb(main):013:0> 10.to_s.class
=> String
irb(main):014:0> 10.to_s.to_i
=> 10
irb(main):015:0> 10.to_s.to_i.class
=> Integer
irb(main):016:0>
.length
irb(main):016:0> "this is a string".length
=> 16
# This method does not work on integers
.reverse
irb(main):018:0> full
=> "Damian Demasi"
irb(main):019:0> full.reverse
=> "isameD naimaD"
irb(main):020:0> full
=> "Damian Demasi"
irb(main):021:0>
.capitalize
irb(main):026:0> full
=> "Damian Demasi"
irb(main):027:0> full.capitalize
=> "Damian demasi"
irb(main):028:0>
.empty?
irb(main):030:0> full
=> "Damian Demasi"
irb(main):031:0> full.empty?
=> false
irb(main):032:0> "".empty?
=> true
.nil?
irb(main):033:0> "".nil?
=> false
irb(main):034:0> nil.nil?
=> true
.sub
and .gsub
irb(main):035:0> msg = "This is wrong"
=> "This is wrong"
irb(main):036:0> msg.sub("is wrong", "will be OK")
=> "This will be OK"
irb(main):037:0>
# We can use .gsub for making global substitutions on longer strings.
The .gsub!
method stands for global substitution.
The syntax looks like this:
string_to_change.gsub!(/s/, "th")
When we get to later lessons, we’ll explain why the /s/
has to be between slashes instead of between quotes. Note: you cannot put a space between gsub!
and the bit in parentheses.
.include?
We can do that using Ruby’s .include?
method, which evaluates to true
if it finds what it’s looking for and false
otherwise.
(As a general rule, Ruby methods that end with ?
evaluate to the boolean values true
or false
.)
if string_to_check.include? "substring"
.sort_by
colors = {
"blue" => 3,
"green" => 1,
"red" => 2
}
colors = colors.sort_by do |color, count|
count
end
colors.reverse!
- In the example above, we first create a hash called
colors
that maps color strings to numbers. - Then, we sort
colors
into green, red, and blue, from smallest to largest by count. Just so you know, the.sort_by
function returns an array of arrays, but that’s fine for our purposes. - Finally, we reverse the array order so that the colors with the largest counts are first.
.sort
What if we wanted to sort the books by title, but from Z – A, or descending order? It appears that Ruby’s sort method only works for A – Z, or ascending order.
The sort
method assumes by default that you want to sort in ascending order, but it accepts a block as an optional argument that allows you, the programmer, to specify how two items should be compared.
books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
# To sort our books in ascending order, in-place
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
# Sort your books in descending order, in-place below
books.sort! { |firstBook, secondBook| secondBook <=> firstBook }
.object_id
The .object_id
method gets the ID of an object—it’s how Ruby knows whether two objects are the exact same object.
.select
Find out available methods on an object
object.methods
irb(main):010:0> "string".methods
=> [:encode, :encode!, :unpack, :unpack1, :include?, :%, :*, :+, :count, :partition, :to_c, :sum, :next, :casecmp, :casecmp?, :insert, :bytesize, :match, :match?, :succ!, :<=>, :next!, :upto, :index, :replace, :==, :===, :chr, :=~, :rindex, :[], :[]=, :byteslice, :getbyte, :setbyte, :clear, :scrub, :empty?, :eql?, :-@, :downcase, :scrub!, :dump, :undump, :upcase, :+@, :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :freeze, :inspect, :bytes, :chars, :codepoints, :lines, :reverse, :reverse!, :concat, :split, :crypt, :ord, :length, :size, :grapheme_clusters, :succ, :start_with?, :center, :prepend, :strip, :rjust, :rstrip, :ljust, :chomp, :delete_suffix, :sub, :to_str, :to_sym, :intern, :sub!, :lstrip, :<<, :to_s, :to_i, :to_f, :gsub!, :chop!, :chomp!, :delete_prefix, :gsub, :chop, :end_with?, :scan, :tr, :strip!, :lstrip!, :rstrip!, :delete_prefix!, :delete_suffix!, :delete!, :tr_s, :delete, :squeeze, :tr!, :tr_s!, :each_grapheme_cluster, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :b, :slice, :slice!, :hash, :encoding, :force_encoding, :unicode_normalize, :valid_encoding?, :ascii_only?, :rpartition, :unicode_normalize!, :unicode_normalized?, :to_r, :between?, :<=, :>=, :clamp, :<, :>, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :instance_variable_set, :instance_variables, :singleton_method, :method, :public_send, :define_singleton_method, :public_method, :extend, :to_enum, :enum_for, :!~, :respond_to?, :object_id, :send, :display, :nil?, :class, :singleton_class, :clone, :dup, :itself, :yield_self, :then, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :equal?, :!, :__id__, :instance_exec, :!=, :instance_eval, :__send__]
Method chaining
irb(main):015:0> 10.to_s.to_i.class
=> Integer
Bang methods
Bang methods end with an exclamation mark (!
), and often modify the object they are called on.
print "This is my question?"
answer = gets.chomp
answer2 = answer.capitalize
answer.capitalize!
This modifies the value contained within the variable answer
itself. The next time you use the variable answer
you will get the results of answer.capitalize