Ruby/Method/Method Creation
Материал из Wiki.crossplatform.ru
Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Add a new method by add method to Class
class String def last(n) self[-n, n] end end p "Here"s a string.".last(7) # => "string."
A simple definition for a method named hello, created with the keywords def and end
def hello puts "Hello, Matz!" end hello # => Hello, Matz!
Call a function for a parameter with or without parenthesis
string = "My first string" # => "My first string" string.count "i" # => 2 # "i" occurs twice. string.count("i") # => 2
Creating and Calling a Method
def greeting puts "Hello, pilgrim." end # As you already know, you call a method simply by giving its name: greeting
Define a method to convert Cartesian (x,y) coordinates to Polar
def polar(x,y) theta = Math.atan2(y,x) # Compute the angle r = Math.hypot(x,y) # Compute the distance [r, theta] # The last expression is the return value end distance, angle = polar(2,2)
define methods that have arguments
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 ?
def probably_prime?(x) x < 8 end puts probably_prime? 2 # => true puts probably_prime? 5 # => true puts probably_prime? 6 # => true puts probably_prime? 7 # => true puts probably_prime? 8 # => false puts probably_prime? 100000 # => false
You can a function with or without parenthesis
string = "My first string" # => "My first string" string.length # => 15 string.length() # => 15
You can call another function based on the return from this funtion call
string = "My first string" # => "My first string" string.length.next # => 16