Skip to content

sf-wdi-44/ruby-methods

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 

Repository files navigation

Ruby Control Flow and Methods

Why is this important?

This workshop is important because:

In order to write Ruby code, you're going to need some practice writing Ruby methods. Once you can divide your Ruby code into methods, you'll have cleaner, more readable code. Learning to design Ruby methods and predict their output is necessary to develop more complex projects (like web sites!).

What are the objectives?

After this workshop, developers will be able to:

  • Write conditionals, loops, and methods in Ruby
  • Apply methods in Ruby to solve problems
  • Explain the two main differences between Ruby methods and JavaScript functions: isolated local scope and implicit return.

Quick review

  1. Make a table with 2 columns. Label one column Ruby and the other column JavaScript. Add at least 3 pieces of JavaScript syntax and the analogous Ruby syntax we've learned.
Ruby JavaScript
p, puts, print console.log()
  1. Identify the operators in Javascript and Ruby, and find differences.

JavaScript operators

  • =, +=, *=, ...

  • ==, ===, >, >=, ...

  • !, ||, &&

  • +, -, /, *

Ruby operators

  • =, +=, *=, ...

  • ==, .equal?, >, >=, ...

  • !, not, ||, &&

  • ** , +, -, /, *

Control flow

Create a demo with one conditional and one loop/iterator:

  • Conditionals
    • if, elsif, else, unless, case when else ...
  • Loops/iterators
    • until, while, .times ...
    • .each, for ... in ...

Blocks

  • block - chunks of code between braces or between do...end:

  • used with .each, .map, and many other methods that let us specify some code to run

[1, 2, 3].each do |n|
  puts "Number #{n}"
end
^ is the same as
[1, 2, 3].each {|n| puts "Number #{n}"}

Further Reading on Blocks

You can think of blocks a little bit like callbacks from JavaScript.

Ruby Methods

The basics

  • Use def, method name, and end when defining a method.
  • Methods implicitly return whatever they last evaluated.
  • Ruby local variables are completely isolated to the exact method they're inside of.

Defining a method

# announce you are creating a method with 'def'
def say_hello
  # all logic and action within belongs to the method
  puts "Hello"
# end your method definition with 'end'
end

# call the method 'say_hello'
say_hello

Defining a method with a parameter

def say(something)
  puts something
end

say('hello')

say 'hello'

Ruby allows us to specify parameters omitting parentheses:

# calling method, not using parentheses
results = method_name parameter1

If you want to chain another method off the result of your method call, you do need parentheses as you can see below:

# You need to use parentheses if you want to work with the result immediately.
# e.g., if a method returns an array and we want to reverse element order:
results = method_name(parameter1).reverse

Parameters can have default values

def say(something = "Hello")
  puts something
end

say # prints "Hello"
say "Goodbye" # prints "Goodbye"

Recursion: methods can call themselves

def recurse(depth)
  if depth > 0
    puts "Spiraling down..."
    recurse(depth - 1)
    puts "Spiraling up..."
  else
    puts "Bottom of the rabbit hole"
  end
end

recurse(5)
recurse 5

Define a method that operates on two parameters

def add_numbers(first, second)
  puts first + second
end

add_numbers(1,2)
add_numbers 1, 2

Define a method that uses a block

def process_number(n=3)
  p 'processing your number'
  yield(n)  #  yield allows you to "inject" a block of code into a function
  p 'all done!'
end


process_number do |num|
  p num * 2 
end

process_number 5 do |i|
  p (0..i).to_a  # to_a is a method that converts an object into an array.
end

Returning in Ruby

Prompt: What is the difference between printing and returning?

Printing and returning are different

The following method returns a value, but doesn't print anything.

def add_numbers_quietly(first, second)
  first + second
end

add_numbers_quietly(1,2)
add_numbers_quietly 1, 2

Methods in Ruby always return the value of the last evaluated expression

def implicitly_return_5
  if true
    5
  end
end

implicitly_return_5

Method scope: the biggest difference from javascript

Prompt: Write some Ruby that demonstrates the scoping of variables.

Functions have locally scoped variables

The following code wont work. Why?

foo = 1

def do_stuff
  foo += 1
  bar = 1
  puts foo
  puts bar
end

do_stuff

puts foo
puts bar

The problem is the ruby is locally scoped. Meaning that a function only has access to its variables and the variables it defined inside of itself.

foo = 1

def do_stuff
  foo = 1
  foo += 1
  bar = 1
  puts foo
  puts bar
end

do_stuff

puts foo
puts bar

def do_stuff2(x)
  foo = x
  foo += 1
  bar = 1
  puts foo
  puts bar
end

puts do_stuff2(foo)

Ruby Method Calls In Depth

You can use the defined? method to check the scope of a variable.

x = 4
=> 4
defined? x
=> "local-variable"

defined? y
=> nil

Exercises

Please complete these exercises.

Further Reading

Releases

No releases published

Packages

No packages published

Languages

  • Ruby 100.0%