我認爲定義一個自定義類的to_s
方法意味着調用該類的puts
方法將返回to_s
指定的輸出。然而,在這個程序中,如果我寫puts bingo_board.to_s
,我只會得到我渴望的結果。到底是怎麼回事?爲什麼不是put方法調用我的.to_s方法?
class BingoBoard < Array
@@letters = %w[B I N G O]
def initialize
# populates an 5x5 array with numbers 1-100
# to make this accessible across your methods within this class, I made
# this an instance variable. @ = instance variable
@bingo_board = Array.new(5) {Array.new(5)}
@bingo_board.each_with_index do |column, i|
rangemin = 15 * i + 1
@bingo_board[i] = (rangemin..(rangemin+14)).to_a.sample(5)
end
@bingo_board[2][2] = "X" # the 'free space' in the middle
@game_over = false
end
def game_over?
@game_over
end
def generate_call
....
end
def compare_call(call)
@bingo_board[@@letters.index(call[0])].include? call[1]
end
def react_to_call(call)
...
end
def check_board
...
end
def show_column(num)
...
end
def to_s
result = ""
0.upto(4) do |val|
result += " " + @@letters[val] + " "
end
result += "\n\n"
0.upto(4) do |row|
0.upto(4) do |col|
val = @bingo_board[col][row]
result += " " if val.to_i < 10
result += val.to_s + " "
end
result += "\n"
end
result
end
end
my_board = BingoBoard.new
counter = 0
until my_board.game_over?
puts my_board.to_s # renders the board in accordance with my to_s method
call = my_board.generate_call
counter += 1
puts "\nThe call \# #{counter} is #{call[0]} #{call[1]}"
my_board.react_to_call(call)
gets.chomp
end
puts my_board # renders bubkes (i.e., nothing)
puts "\n\n"
puts "Game over"
哇!這是一個快速解決方案。但是Array有自己的to_s方法。爲什麼我的自定義to_s方法無法覆蓋它,@jwater? – pgblu 2014-10-19 17:21:21
tl;你離開我的鏈接的博士:數組的處理方式不同,沒有人真正知道爲什麼。這是一個公平的總結嗎? 另外:是否準確地說數組to_s方法不能被覆蓋? – pgblu 2014-10-19 17:29:23
@pgblu - 不完全是,它被覆蓋,如果你使用其他方法如say,print,它會調用你的to_s,但只要你使用puts方法,那麼你是對的。 – jwater 2014-10-19 17:38:31