Create a gist now

Instantly share code, notes, and snippets.

Methods tap and itself in Crystal (for blogpost http://veelenga.com/tap-and-itself-methods-in-crystal/)
################################################################################
p 10.itself # 10
p "1".itself # "1"
p :sym.itself # :sym
p true.itself # true
p nil.itself # nil
p [1, 2].itself # [1, 2]
p ({"1" => "2"} of String => String).itself # {"1" => "2"}
p /1/.itself # /1/
################################################################################
p [1,2,4,1,2,2,3].group_by {|x| x} # {1 => [1, 1], 2 => [2, 2, 2], 4 => [4], 3 => [3]}
p [1,2,4,1,2,2,3].group_by &.itself # {1 => [1, 1], 2 => [2, 2, 2], 4 => [4], 3 => [3]}
################################################################################
class Team
def initialize
@players = [] of String
end
def <<(player)
@players << player
end
def any?
@players.each {|player| return true if yield player}
false
end
def any?
any? &.itself
end
end
team = Team.new.tap do |t|
t << "Player1"
t << "Player2"
t << "Player3"
end
p team.any? # true
p team.any? {|player| player =~ /2/} # true
p team.any? {|player| player =~ /4/} # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment