以下代码导致nil,我无法弄清楚原因。我的初始化有问题吗?
class Card
VALUES = %w(2 3 4 5 6 7 8 9 10 J Q K A)
SUITS = %w(S H D C)
def initialize(suit, value)
@suit = suit
@value = value
end
end
class Deck
attr_accessor :cards
def initialize
@cards = []
Card::SUITS.each do |suit|
Card::VALUES.each do |value|
@cards << Card.new(suit, value)
end
end
end
end
Deck.new
p @cards
答案 0 :(得分:1)
curl $(docker-machine ip default):49160
。在类@cards
之外,它是Ruby中顶级作用域的实例变量。
您必须使用访问者方法来获取内容:
Deck
答案 1 :(得分:1)
或只是:
my_deck = Deck.new
p my_deck.cards
答案 2 :(得分:1)
简而言之,实例变量只能通过同一类中的其他方法来查看。我相信你要做的是:
new_deck = Deck.new
p new_deck.cards
在cards
上调用new_deck
方法会返回@cards
。
答案 3 :(得分:0)
您创建了一个新对象Deck.new
,但是您不打印其cards
的值 - 您打印的@cards
实例变量在此上下文中为{{1} }}
你可能想要像nil
这样的东西。
答案 4 :(得分:0)
目前,@cards
数组的输出很难读取并包含对象信息。我以为我会提供另一种选择,我希望它有所帮助:
class Deck
attr_writer :suits, :values
attr_accessor :deck
def initialize
suits
values
generate_deck
shuffle
end
def generate_deck
@deck = []
@suits.each do |suit|
@values.each { |value| @deck << [suit, value] }
end
end
def suits
@suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades' ]
end
def values
@values = ('2'..'10').to_a + ['J','Q','K','A']
end
#just in case you want to shuffle your deck
def shuffle
@deck.shuffle!
end
end
require 'pp' #this makes the output prettier
new_deck = Deck.new
pp new_deck.deck #calls your current deck so you can see it
输出示例:
$ ruby yourfilename.rb
[["Hearts", "K"],
["Spades", "5"],
["Clubs", "7"],
#code omitted... (the rest of your cards would be here)
["Clubs", "K"],
["Hearts", "5"],
["Diamonds", "J"],
["Hearts", "7"]]