2012-05-04 12 views

risposta

28

L'istruzione return funziona nello stesso modo in cui funziona su altri linguaggi di programmazione simili, ma restituisce solo il metodo utilizzato. È possibile saltare la chiamata per tornare, poiché tutti i metodi in ruby ​​restituiscono sempre l'ultima istruzione. Così si potrebbe trovare metodo come questo:

def method 
    "hey there" 
end 

Questo è in realtà lo stesso di fare qualcosa di simile:

def method 
    return "hey there" 
end 

La yield d'altra parte, excecutes il blocco specificato come parametro al metodo. Così si può avere un metodo come questo:

def method 
    puts "do somthing..." 
    yield 
end 

E poi usare in questo modo:

method do 
    puts "doing something" 
end 

il risultato di questo, sarebbero stampa sullo schermo le seguenti 2 linee:

"do somthing..." 
"doing something" 

Spero che si risolva un po '. Per maggiori informazioni sui blocchi, è possibile controllare this link.

+0

Il link ai blocchi è rotto – adamscott

+1

Ecco un buon collegamento [link] (http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes) – adamscott

+0

grazie @adamscott, ho cambiato il link con il tuo. Saluti – Deleteman

6

yield viene utilizzato per chiamare il blocco associato al metodo. Si esegue l'operazione posizionando il blocco (fondamentalmente solo codice tra parentesi graffe) dopo il metodo ei suoi parametri, in questo modo:

[1, 2, 3].each {|elem| puts elem} 

return esce dal metodo corrente e utilizza il suo "argomento" come valore di ritorno, in questo modo:

def hello 
    return :hello if some_test 
    puts "If it some_test returns false, then this message will be printed." 
end 

ma nota che non hanno di utilizzare la parola chiave return in qualsiasi metodo; Ruby restituirà l'ultima istruzione valutata se non incontra ritorni. Così questi due sono equivelent:

def explicit_return 
    # ... 
    return true 
end 

def implicit_return 
    # ... 
    true 
end 

Ecco un esempio per yield:

# A simple iterator that operates on an array 
def each_in(ary) 
    i = 0 
    until i >= ary.size 
    # Calls the block associated with this method and sends the arguments as block parameters. 
    # Automatically raises LocalJumpError if there is no block, so to make it safe, you can use block_given? 
    yield(ary[i]) 
    i += 1 
    end 
end 

# Reverses an array 
result = []  # This block is "tied" to the method 
       #       | | | 
       #       v v v 
each_in([:duck, :duck, :duck, :GOOSE]) {|elem| result.insert(0, elem)} 
result # => [:GOOSE, :duck, :duck, :duck] 

e un esempio per return, che io uso per implementare un metodo per vedere se un numero è happy :

class Numeric 
    # Not the real meat of the program 
    def sum_of_squares 
    (to_s.split("").collect {|s| s.to_i ** 2}).inject(0) {|sum, i| sum + i} 
    end 

    def happy?(cache=[]) 
    # If the number reaches 1, then it is happy. 
    return true if self == 1 
    # Can't be happy because we're starting to loop 
    return false if cache.include?(self) 
    # Ask the next number if it's happy, with self added to the list of seen numbers 
    # You don't actually need the return (it works without it); I just add it for symmetry 
    return sum_of_squares.happy?(cache << self) 
    end 
end 

24.happy? # => false 
19.happy? # => true 
2.happy? # => false 
1.happy? # => true 
# ... and so on ... 

Spero che questo aiuti! :)

+0

grazie per la risposta :) – nxhoaf

+0

sì, nessun problema!:) – Jwosty

+0

@Jwosty non dovrebbe essere 'def happy? (Cache = [])'? –

0
def cool 
    return yield 
end 

p cool {"yes!"} 

La parola chiave yield indica a Ruby di eseguire il codice nel blocco. In questo esempio, il blocco restituisce la stringa "yes!". Nel metodo cool() è stata utilizzata una dichiarazione di reso esplicita, ma anche questo potrebbe essere implicito.