Coder Social home page Coder Social logo

ruby-methods's Introduction

Ruby Control Flow and Methods

Objectives:
Identify control flow patterns and functions in Ruby
Apply control flow to create command line applications
Apply methods in ruby to solve problems

History

Ruby was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. Ruby on Rails, or simply Rails, is a web application framework written in Ruby.

Parts of A Language

  • Primitives
  • Combinations
  • Abstractions

Ruby vs. JS Primitives

Let's recall some of our JS Data Types

Javascript

  • null, undefined
  • Strings
  • Booleans
  • Number
    • .toString
  • Arrays indexOf,splice, slice
  • Objects
    • ["some_key"], .some_key
  • operators
    • ==, ===, >, >=, ..
    • !, ||, &&
    • +, -, /, *
  • Console methods
    • console.log
    • prompt

Ruby

  • nil
  • Integers
    • Fixnum
    • Bignum
    • to_s
  • Floats
  • Strings
    • .to_i and .to_f *INTEGER
  • Symbols
  • Booleans
  • Arrays / Ranges
    • [x..y], [x...y], index
  • Hashes
    • { :key => value }
    • { key: value } which is the same as {:key =>value }
    • [some_key] and [some_key]=
    • key,.keys, .each
  • operators
    • ||=, *=, /=
    • ==, .equal?,
    • !, not, ||, &&
    • **, +, -, /, *
  • General Delimited Input
    • %w, %r
  • Console Methods
    • puts, p
    • gets and gets.chomp

Control flow

  • Conditionals
    • if, else if, else, switch, ...
  • Loops
    • do-while, while, ...
  • iterators,
    • for-in
  • Exceptions
    • try, catch
  • Conditionals
    • if, elsif, else, unless, case when else ...
  • Loops
    • until, while, times ...
  • iterators,
    • .each, for ... in
  • Exceptions
    • begin, rescue, ensure

Some Abstractions

Javascript

  • Function
    • Anonymous: function (param1, [..param2, [...]]){...},
    • Named: function Name(param1, [..param2, [...]]){...}
    • Uses lexical scope
    • Used as values
    • require explicit return
    • all params are optional

Ruby

  • Function

    • uses def
    • Do not capture scope
    • Not used as values
    • optional parameters must be specified
    • implicitly returns last evaluation
  • block

    • used with .each, .map, et cetera
    [1, 2, 3].each do |n|
      puts "Number #{n}"
    end

    ^ is the same as

    [1, 2, 3].each {|n| puts "Number #{n}"}
    • captures scope

Further Reading on Blocks

#Ruby Methods

Define 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 defniition with 'end'
end

# call the method 'say_hello'
say_hello

Define a method with a parameter

def say(something)
  puts something
end

say('hello')

say 'hello'

If you don't have code that needs to use method result immediately, Ruby allows us to specify parameters omitting parentheses:

# calling method, not using parentheses
results = method_name parameter1

# 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

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

Printing and returning are different

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
  • What was the value of the if statement?
  • status_of_world = if 1 == 2 then "messed up" else "a-o-k" end
  • result = 1 == 2 ? "wuh oh" : "phew"

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

The biggest difference from javascript

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

Exercises

Please complete these exercises.

Further Reading

ruby-methods's People

Contributors

ben-manning avatar

Watchers

James Cloos avatar Paolo Sese avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.