Re-namespacing a bit to clear out some fairly old stuff from the top level
This commit is contained in:
28
oldstuff/RubyFun/cookbook/007/01.rb
Normal file
28
oldstuff/RubyFun/cookbook/007/01.rb
Normal file
@@ -0,0 +1,28 @@
|
||||
# WRONG
|
||||
# aBlock = { |x| puts x }
|
||||
|
||||
# RIGHT
|
||||
aBlock = lambda { |x| puts x }
|
||||
|
||||
aBlock.call "Hello World!"
|
||||
|
||||
|
||||
def my_lambda(&aBlock)
|
||||
aBlock
|
||||
end
|
||||
|
||||
b = my_lambda { puts "Hello World My Way!" }
|
||||
b.call
|
||||
|
||||
aBlock = Proc.new { |x| puts x }
|
||||
aBlock = proc { |x| puts x }
|
||||
aBlock = lambda { |x| puts x }
|
||||
|
||||
add_lambda = lambda { |x,y| x + y }
|
||||
# add_lambda.call(4)
|
||||
# add_lambda.call(4,5,6)
|
||||
puts add_lambda.call(4,2)
|
||||
|
||||
add_procnew = Proc.new { |x,y| x + y }
|
||||
# add_procnew.call(4)
|
||||
puts add_procnew.call(4,5,6)
|
30
oldstuff/RubyFun/cookbook/007/02.rb
Normal file
30
oldstuff/RubyFun/cookbook/007/02.rb
Normal file
@@ -0,0 +1,30 @@
|
||||
require 'pp'
|
||||
|
||||
def call_twice
|
||||
puts "Calling your block."
|
||||
ret1 = yield("very first")
|
||||
puts "The value of your block: #{ret1}"
|
||||
|
||||
puts "Calling your block again."
|
||||
ret2 = yield("second")
|
||||
puts "The value of your block: #{ret2}"
|
||||
end
|
||||
|
||||
call_twice do |which_time|
|
||||
puts "I'm a code block, called for the #{which_time} time."
|
||||
which_time == "very first" ? 1 : 2
|
||||
end
|
||||
|
||||
|
||||
class Hash
|
||||
def find_all
|
||||
new_hash = Hash.new
|
||||
each { |k,v| new_hash[k] = v if yield(k, v) }
|
||||
new_hash
|
||||
end
|
||||
end
|
||||
|
||||
squares = {0=>0, 1=>1, 2=>4, 3=>9}
|
||||
print "squares = "
|
||||
pp squares
|
||||
(squares.find_all { |key, value| key > 1 }).each { |k,v| puts "#{k}: #{v}" }
|
39
oldstuff/RubyFun/cookbook/007/intro.rb
Normal file
39
oldstuff/RubyFun/cookbook/007/intro.rb
Normal file
@@ -0,0 +1,39 @@
|
||||
[1, 2, 3].each { |i| puts i }
|
||||
|
||||
[1, 2, 3].each do |i|
|
||||
if i % 2 == 0
|
||||
puts "#{i} is even."
|
||||
else
|
||||
puts "#{i} is odd."
|
||||
end
|
||||
end
|
||||
|
||||
1.upto 3 do |x|
|
||||
puts x
|
||||
end
|
||||
|
||||
1.upto(3) { |x| puts x }
|
||||
|
||||
hello = lambda { "Hello" }
|
||||
hello.call
|
||||
|
||||
log = lambda { |str| puts "[LOG] #{str}" }
|
||||
log.call("A test log message.")
|
||||
|
||||
{1=>2, 2=>4}.each { |k,v| puts "Key #{k}, value #{v}" }
|
||||
|
||||
def times_n(n)
|
||||
lambda { |x| x * n }
|
||||
end
|
||||
|
||||
times_ten = times_n(10)
|
||||
puts times_ten.call(5)
|
||||
puts times_ten.call(1.25)
|
||||
|
||||
circumference = times_n(2*Math::PI)
|
||||
puts circumference.call(10)
|
||||
puts circumference.call(3)
|
||||
puts [1, 2, 3].collect(&circumference)
|
||||
|
||||
ceiling = 50
|
||||
puts [1, 10, 49, 50.1, 200].select { |x| x < ceiling }
|
Reference in New Issue
Block a user