Ruby 异常处理与模式匹配全解析
1. Ruby 模式匹配基础
在 Ruby 中,模式匹配是一种强大的特性,它允许我们根据特定的模式来匹配数据。例如,在处理扑克牌时,可以使用模式匹配来判断手中的牌是否有特定的组合。
class Card
attr_reader :rank, :suit
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def deconstruct_keys(keys)
{ rank: @rank, suit: @suit }
end
end
def pick_a_card(cards)
cards = cards.sort_by(&:rank)
case cards
in [{rank:}, {rank: ^(rank + 1)}, {rank: ^(rank + 2)}] if rank > 6
"You have three consecutive high cards"
else
"You have no interesting cards,"
end
end
puts pick_a_card([
Card.new(7, "Hearts"),
Card.new(8, "Diamonds"),
Card.new(9, "Clubs")
])
上述代码中, pick_a_card 函数接收一个扑克牌数组,通过 sort_by(&:rank) 对
超级会员免费看
订阅专栏 解锁全文
159

被折叠的 条评论
为什么被折叠?



