Ruby/Method/return
Материал из Wiki.crossplatform.ru
Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Because it"s returning multiple values from a method, Ruby returns an array:
def greeting() return "No", "worries" end array = greeting
Return a Value from a Method
number = 3 def incrementer(value) return value + 1 end puts number.to_s + " + 1 = " + incrementer(number).to_s
Returning a Value from a Method
def adder(operand_one, operand_two) return operand_one + operand_two end adder "Hello ", "Hello "
Returning Multiples Values from a Method
# Ruby uses arrays to return multiple values. # To return multiple values, all you have to do is to separate them with a comma: return a, b, c def greeting() return "No", "worries" end array = greeting puts array.join(" ")
Return the index of the first occurrence of target within array or nil
def find(array, target) array.each_with_index do |element,index| return index if (element == target) # return from find end nil # If we didn"t find the element, return nil end
Return two copies of x, if x is not nil
def double(x) return nil if x == nil # Return prematurely return x, x.dup # Return multiple values end
Return values from function without using return statement
def perimeter_of_square(side_length) side_length * 4 end def area_of_square(side_length) side_length * side_length end def perimeter_of_triangle(side1, side2, side3) side1 + side2 + side3 end def area_of_triangle(base_width, height) base_width * height / 2 end puts area_of_triangle(6,6) puts perimeter_of_square(5)
Ruby makes it easy to handle multiple return values - no need to work with arrays explicitly at all.
# All you have to do is to assign the return value of the called method to a comma-separated list of variables def greeting() return "No", "worries" end word_one, word_two = greeting
Ruby returns the last value calculated, you can omit the return keyword if you want.
def adder(operand_one, operand_two) operand_one + operand_two end
String interpolation with method call
def say_goodnight(name) "Good night, #{name}" end puts say_goodnight("Ma")