Proc und Lambda in Ruby
Level 5278 Tastenanschläge
Erzeugt ein Proc und ein Lambda, übergibt sie mit & an map, um eine Liste zu quadrieren und zu kubieren, und ruft dann beide mit 5 auf.
Ruby-Code
# Ein Proc-Objekt, das einen Block kapselt1square = Proc.new { |x| x * x }# -> erzeugt ein Lambda, das die Anzahl der Argumente streng prüft2cube = ->(x) { x * x * x }3 4numbers = [1, 2, 3, 4, 5]5 # & macht das Proc zum Block für map6squares = numbers.map(&square)# Ein Lambda lässt sich genauso übergeben7cubes = numbers.map(&cube)8 # Die Interpolation eines Arrays nutzt inspect: "Squares: [1, 4, 9, 16, 25]"9puts "Squares: #{squares}"# Gibt "Cubes: [1, 8, 27, 64, 125]" aus10puts "Cubes: #{cubes}"11 # Procs und Lambdas sind Objekte und lassen sich in einem Array speichern12operations = [square, cube]13operations.each do |op| # call führt jedes mit 5 aus: gibt "5 -> 25", dann "5 -> 125" aus14 puts "5 -> #{op.call(5)}"15endAusgabe
Squares: [1, 4, 9, 16, 25] Cubes: [1, 8, 27, 64, 125] 5 -> 25 5 -> 125
Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.
Symbole in diesem Code
Die Symbole, die du in diesem Ruby-Code tippst, und wie oft sie vorkommen.
"× 6=× 6,× 5.× 5{× 5}× 5(× 4)× 4|× 4*× 3