Skip to content

Instantly share code, notes, and snippets.

@jkischkel
Created February 23, 2015 09:17
Show Gist options
  • Save jkischkel/de25607c4ad001dc114f to your computer and use it in GitHub Desktop.
Save jkischkel/de25607c4ad001dc114f to your computer and use it in GitHub Desktop.
Ruby Blocks
# a simple block:
p [1,2,3].map { |i| i.to_s }
# a block with do/end
p [1,2,3].map do |i|
i.to_s
end
# even fancier, with a function reference
p [1,2,3].map(&:to_s)
# passing a block to a function
def with_block
if block_given?
yield
else
"This is the default."
end
end
p with_block
p with_block { "Hello" }
# passing a block to a function with arguments
def with_name
puts "Enter your name:"
name = gets.chomp
yield(name)
end
with_name { |n| "Hallo #{n}!" }
with_name { |n| "#{n} backward is #{n.reverse}" }
# having regular arguments plus a block
def with_double(i)
yield(i * 2)
end
with_double(5) { |number| puts "This project will take #{ number } months to finish" }
class SimpleCalc
def +(a, b)
a + b
end
def -(a, b)
a - b
end
end
calc = SimpleCalc.new
calc.+(2, 3)
calc.-(2, 3)
class GenericCalc
def +(a, b)
a.to_i + b.to_i
end
def -(a, b)
a.to_i - b.to_i
end
end
calc = GenericCalc.new
calc.+("2", 3)
calc.-(2, "3")
class GenericCalc
def +(a, b)
puts "input values are (#{a},#{b})"
a.to_i + b.to_i
end
def -(a, b)
puts "input values are (#{a},#{b})"
a.to_i - b.to_i
end
end
calc = GenericCalc.new
calc.+("2", 3)
calc.-(2, "3")
class UberCalc
def +(a, b)
exec(a, b) { |a, b| a + b }
end
def -(a, b)
exec(a, b) { |a, b| a - b }
end
private
def exec(a, b)
puts "input values are (#{a},#{b})"
yield(a.to_i, b.to_i)
end
end
calc = UberCalc.new
calc.+("2", 3)
calc.-(2, "3")
class MegaUberCalc2000
def +(a, b)
exec(a, b, &:+)
end
def -(a, b)
exec(a, b, &:-)
end
private
def exec(a, b)
puts "input values are (#{a},#{b})"
yield(a.to_i, b.to_i)
end
end
calc = MegaUberCalc2000.new
calc.+("2", 3)
calc.-(2, "3")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment