在纸牌游戏桥牌中,四张牌被赋予点值:Jack:1,Queen:2,King:3,Ace:4。给定一手牌对应的字符串数组(纸牌表示如下: ["2","3","4","5","6","7","8","9","10","J","Q","K", "A"]), 返回该手牌的大牌总点数。
我可以用 while
循环解决这个简单的问题,但我也想学习如何使用 .each
遍历数组,这是我的代码那行不通
def high_card_points(hand)
sum = 0
hand.each do |i|
if hand[i] == "J"
sum += 1
elsif hand[i] == "Q"
sum += 2
elsif hand[i] == "K"
sum += 3
elsif hand[i] == "A"
sum += 4
end
end
sum
end
现在,当我运行它时,出现错误 no implicit conversion of String into Integer
。我应该如何以正确的方式去做?
这里的问题是,当你在 block 中使用每个变量时,数组中的对象不是索引,所以你可以按如下方式工作:
def high_card_points(hand)
sum = 0
hand.each do |card|
if card == "J"
sum += 1
elsif card == "Q"
sum += 2
elsif card == "K"
sum += 3
elsif card == "A"
sum += 4
end
end
sum
end
如果你偷偷执行
[5] pry(main)* => :high_card_points
[6] pry(main)> high_card_points(cards)
=> 10
您也可以像使用 each_index
一样使用索引。但您也可以采用其他对象功能方法:
您可以创建您的类或猴子修补类字符串:
class String
def card_points
case self
when 'J'
1
when 'Q'
2
when 'K'
3
when 'A'
4
else
0
end
end
end
然后像这样进行:
[31] pry(main)> cards.map(&:card_points).inject(0, :+)
=> 10
我是一名优秀的程序员,十分优秀!