Tutorial by Examples

def say_hello_to(name) puts "Hello #{name}" end say_hello_to('Charles') # Hello Charles
def greet(greeting, name) puts "#{greeting} #{name}" end greet('Hi', 'Sophie') # Hi Sophie
def make_animal_sound(sound = 'Cuack') puts sound end make_animal_sound('Mooo') # Mooo make_animal_sound # Cuack It's possible to include defaults for multiple arguments: def make_animal_sound(sound = 'Cuack', volume = 11) play_sound(sound, volume) end make_animal_so...
def welcome_guests(*guests) guests.each { |guest| puts "Welcome #{guest}!" } end welcome_guests('Tom') # Welcome Tom! welcome_guests('Rob', 'Sally', 'Lucas') # Welcome Rob! # Welcome Sally! # W...
def my_mix(name,valid=true, *opt) puts name puts valid puts opt end Call as follows: my_mix('me') # 'me' # true # [] my_mix('me', false) # 'me' # false # [] my_mix('me', true, 5, 7) # 'me' # true # [5,7]
Defining a method in Ruby 2.x returns a symbol representing the name: class Example puts def hello end end #=> :hello This allows for interesting metaprogramming techniques. For instance, methods can be wrapped by other methods: class Class def logged(name) original_method...
The ** operator works similarly to the * operator but it applies to keyword parameters. def options(required_key:, optional_key: nil, **other_options) other_options end options(required_key: 'Done!', foo: 'Foo!', bar: 'Bar!') #> { :foo => "Foo!", :bar => "Bar!" ...
You can send a block to your method and it can call that block multiple times. This can be done by sending a proc/lambda or such, but is easier and faster with yield: def simple(arg1,arg2) puts "First we are here: #{arg1}" yield puts "Finally we are here: #{arg2}" ...
A method can take an array parameter and destructure it immediately into named local variables. Found on Mathias Meyer's blog. def feed( amount, (animal, food) ) p "#{amount} #{animal}s chew some #{food}" end feed 3, [ 'rabbit', 'grass' ] # => "3 rabbits chew some gra...
Methods are defined with the def keyword, followed by the method name and an optional list of parameter names in parentheses. The Ruby code between def and end represents the body of the method. def hello(name) "Hello, #{name}" end A method invocation specifies the method name, the...
Many functions in Ruby accept a block as an argument. E.g.: [0, 1, 2].map {|i| i + 1} => [1, 2, 3] If you already have a function that does what you want, you can turn it into a block using &method(:fn): def inc(num) num + 1 end [0, 1, 2].map &method(:inc) => [1, 2, 3]...

Page 1 of 1