Created
September 24, 2015 10:18
-
-
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/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################################ | |
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