Ruby/Method/Method Arguments

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Block as the third parameter

def zeno(start, stop)
  distance = stop - start
  travelled = start
  while travelled < stop and distance > 0
    yield travelled
    distance = distance / 2.0
    travelled += distance
  end
end
steps = 0
zeno(0, 1) { steps += 1 }
steps                                                  # => 54



Call method from parameter

def endless_string_succession(start)
  while true
    yield start
    start = start.succ
  end
end
endless_string_succession("fol") do |x|
  puts x
  break if x[-1] == x[-2]
end
# fol
# fom
# fon
# foo



Default Arguments

def repeat( word="Hello! ", times=3 )
 puts word * times
end
repeat # => Hello! Hello! Hello!
repeat( "Goodbye! ", 5 ) # => Goodbye! Goodbye! Goodbye! Goodbye! Goodbye!



Function with two parameters

#!/usr/bin/env ruby
def repeat( word, times )
  puts word * times
end
repeat( "Hello! ", 3) # => Hello! Hello! Hello!
repeat "Good-bye! ", 4 # => Good-bye! Good-bye! Good-bye! Good-bye!



Method with three parameters

def putter(first_word, second_word, third_word)
  puts first_word + " " + second_word + " " + third_word
end
putter "Hello", "from", "Ruby."



Pass full arrays to methods in Ruby, and return arrays as well

array = [1, 2, 3, 4]
def returner(array)
  return array
end
array2 = returner(array)
puts array2



Passing Arguments to a Method

def greeting(message)
  puts message
end
greeting("Hello from Ruby.")



Passing Data to Methods with or without parenthesis

puts "Hello, world!"
puts("Hello, world!")



raise ArgumentError

def inverse(x)
  raise ArgumentError, "Argument is not numeric" unless x.is_a? Numeric
  1.0 / x
end



Raise exception based on parameter type

def inverse(x)
  raise "Argument is not numeric" unless x.is_a? Numeric
  1.0 / x
end
inverse(2)                               # => 0.5
inverse("not a number")
# RuntimeError: Argument is not numeric



The parentheses in the call are optional

def greeting(message)
  puts message
end
 
greeting "Hello from Ruby."



Writing a Method that Accepts a Block

def call_twice
  puts "I"m about to call your block."
  yield
  puts "I"m about to call your block again."
  yield
end
call_twice { puts "Hi, I"m a talking code block." }
# I"m about to call your block.
# Hi, I"m a talking code block.
# I"m about to call your block again.
# Hi, I"m a talking code block.