字符串的未定义方法“ push”

时间:2018-11-23 03:05:10

标签: arrays ruby methods

我正在研究一个复制Go Fish的项目,因此我可以了解有关构建数据以及如何正确使用数组的更多信息。我在尝试弄清楚为什么仍然收到此错误时遇到了一些麻烦。我尝试将变量更改为实例变量,这似乎并没有太大帮助。我希望有人可以偷看我的代码并指出正确的方向。 **即使与问题无关,也请提出任何建议。我不知道我是否正确地解决了这个问题。

card_deck = ["ace of spades", "ace of diamonds", "ace of clubs", "ace of hearts",
"two of spades", "two of diamonds", "two of hearts", "two of clubs",
"three of spades", "three of diamonds", "three of hearts", "three of clubs",
"four of spades", "four of diamonds", "four of hearts", "four of clubs",
"five of spades", "five of diamonds", "four of hearts", "five of clubs",
"six of spades", "six of diamonds", "six of hearts", "six of clubs",
"seven of spades", "seven of diamonds", "seven of hearts", "seven of clubs",
"eight of spades", "eight of diamonds", "eight of hearts", "eight of clubs",
"nine of spades", "nine of diamonds", "nine of hearts", "nine of clubs",
"ten of spades", "ten of diamonds", "ten of hearts", "ten of clubs",
"jack of spades", "jack of diamonds", "jack of hearts", "jack of clubs",
"queen of spades", "queen of diamonds", "queen of hearts", "queen of clubs",
"king of spades", "king of diamonds", "king of hearts", "king of clubs"]

puts "There are #{card_deck.length} cards in this deck."
puts "Welcome to Go-Fish."
print "Your name please: "
player_name = $stdin.gets.chomp.capitalize

puts "Ok #{player_name}, lets get this deck shuffled..."
#sleep(1)
# shuffles card_deck using .shuffle method
card_deck = card_deck.shuffle
puts "Cards are perfectly shuffled!"
#sleep(1)
puts "Dealing cards..."
#sleep(1)
# assigns first 7 cards to user
@my_hand = Array.new
@my_hand = card_deck[0..6].join(', ')
# assigns next 7 cards to CPU
@cpu_hand = Array.new
@cpu_hand = card_deck[7..13]

# removes first 14 cards from the deck (0-13)
@card_deck = card_deck.drop(13)

puts "Here's your hand: #{@my_hand}."
puts "You go first!"
puts "Do you have a..."
puts @cpu_hand.join(', ')
print "> "
@card = $stdin.gets.chomp.downcase

# if cpu has the card requested give it to the player and add to their array

if @cpu_hand.include?(@card)
  @my_hand.push(@card)
else
puts "Go fish!"
end

2 个答案:

答案 0 :(得分:1)

推送方法

a = [ "a", "b", "c" ]
a.push("d", "e", "f")
        #=> ["a", "b", "c", "d", "e", "f"]
[1, 2, 3,].push(4).push(5)
        #=> [1, 2, 3, 4, 5]

join方法

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-")   #=> "a-b-c"

答案 1 :(得分:0)

如果要从卡组中取出前7张牌并将其放在玩家手中,则需要执行以下操作:

@my_hand = card_deck.shift(7)

之后,您可以将下7张卡分配给CPU:

@cpu_hand = card_deck.shift(7)

此后无需制作drop。 另外,drop(13)会精确删除13个元素,而不是14(0-13)。

此外,您可能希望使用较短版本的卡座初始化:

cards = ['ace','one','two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king']
suits = ['spades', 'clubs', 'diamonds','hearts']
card_deck = cards.product(suits).collect{|x,y| "#{x} of #{y}"}