ruby - Method behaving differently for 2 classes using same module method -
i had previous question asked here: i (think) i'm getting objects returned when expect array have 2 properties available may give background. having received solution that, moved showing each player hand. below module included in both dealer , player classes.
module hand def show_hand if self.class == dealer #need cover 1 of 2 cards here. dealer doesn't show both! print "the dealer showing: " print self.hand[0].show_card puts '' elsif self.class == player print "you have: " self.hand.each |item| item.show_card end puts '' else puts "a random person showing hand." end end end
i know customization defeats purpose of module, using reinforce concept of modules. above solution worked fine dealer portion. when player portion called printed blank block. on .inspect of each "item" in player block confirmed items in fact card objects expected. here previous show_card method:
def show_card "[#{@card_type} of #{@suit}]" end
so returned string card_type , suit. able fix problem player object portion changing method this:
def show_card print "[#{@card_type} of #{@suit}]" end
why happening? i'm assuming has call "each" on player hand. curious difference , why these card objects wouldn't print without explicit "print" in there vice returning via string object.
hope descriptive enough. 1 baffles me , i'm trying grasp these little things since know prevent future errors this. thanks!
in ruby must print puts
or print
. returning string doesn't print it. reason dealer class prints because did print
, in player
class, noted, had no print. returned string without printing.
as noted, able fix including print:
def show_card print "[#{@card_type} of #{@suit}]" end
you instead:
def show_card "[#{@card_type} of #{@suit}]" end ... module hand def show_hand if self.class == dealer #need cover 1 of 2 cards here. dealer doesn't show both! print "the dealer showing: " puts self.hand[0].show_card # print card elsif self.class == player print "you have: " self.hand.each |item| print item.show_card # print card end puts '' else puts "a random person showing hand." end end end
which little more "symmetrical" , prints want.
a more compact be:
def show_card "[#{@card_type} of #{@suit}]" end ... module hand def show_hand if self.class == dealer #need cover 1 of 2 cards here. dealer doesn't show both! puts "the dealer showing: #{self.hand[0].show_card}" elsif self.class == player print "you have: " self.hand.each { |item| print item.show_card } puts '' else puts "a random person showing hand." end end end
Comments
Post a Comment