Skip to content

Instantly share code, notes, and snippets.

@veelenga
Created September 24, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veelenga/d35b6a2cd002de90f1a7 to your computer and use it in GitHub Desktop.
Save veelenga/d35b6a2cd002de90f1a7 to your computer and use it in GitHub Desktop.
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