learn_ruby_ch2_pt5 Flashcards
User alias (greet, ahello)
def greet
puts “hello”
end
alias ahello greet
ahello
A block to iterate through pacific
A block in Ruby is more than just a code block or group of statements
pacific = [ “Washington”, “Oregon”, “California” ]
pacific.each do |element|
puts element
end
or
pacific.each { |e| puts e }
Use yield to run a block of code (gimme)
def gimme if block_given? yield else puts "I'm blockless!" end end
gimme { print “Say hi.” } # => Say hi.
gimme # => I’m blockless!
Use proc and lambda
count, your_proc, my_proc
!/usr/bin/env ruby
count = Proc.new { [1,2,3,4,5].each do |i| print i end; puts } your_proc = lambda { puts "Lurch: 'You rang?'" } my_proc = proc { puts "Morticia: 'Who was at the door, Lurch?'" }
# What kind of objects did you just create? puts count.class, your_proc.class, my_proc.class
Calling all procs
count.call
your_proc.call
my_proc.call
create a symbol
name = “Matz”
symbols are like placeholders for identifiers and strings
name = “Matz”
name.to_sym # => :Matz
:Matz.id2name # => “Matz”
name == :Matz.id2name # => true
Symbol.all_symbols # about 1000 symbols
Get info on print in the ruby kernel
ri Kernel.print
requires ruby-doc.noarch