I am trying to pass a defined array into a method. Ruby is interpreting
it as an undefined local variable. Is there a way around this?
See comments below in your code...
Also, can
a def method take a string and an array as parameters?
Absolutely, as you have it below should work fine.
player1 = [ ["Ten", 10, "Hearts"], ["King", 13, "Clubs"], ["Queen", 12,
"Clubs"], ["Three", 3, "Clubs"], ["Ten", 10, "Clubs"], ["Jack", 10,
"Clubs"], ["Ten", 2, "Diamonds"] ]
def check_for_flush(suit, player)
occurrences_of_suit = 0
player1.each do |subarray|
Maybe a typo here: you are passing in player in the call, should this be
player.each instead?
If not -- player1 is a local variable inside the method
check_for_flush and has not been defined as anything, so it's nil, and
you can't take .each of a nil.
An aside, it's generally peferrable to give variables meaningful
names, even in loops (which each is). I suggest, given the context,
you change subarray to card.
if subarray[2].downcase == "#{suit}"
You're passing in upper case values for suit below; maybe you want to
change downcase to upcase here.
occurrences_of_suit += 1
end
end
From here on, I'm really rather confused what you're trying to do here...
suit_hand =
if suit >= 5
$player1.each do |subarray|
if subarray[2] == "#{suit}"
suit_hand << subarray
end
end
end
puts suit_hand.inspect
end
check_for_flush ('Clubs' )
You defined two parameters for this method above; this should probably be
check_for_flush('Clubs', player1)
check_for_flush ('Spades', player1 )
check_for_flush ('Diamonds', player1 )
check_for_flush ('Hearts', player1 )
# I would also like to create a parameter player so that I can load
different arrays into the method.
You already did this:
def check_for_flush(suit, player)
At some point, you may want to look into understanding functions
beyond .each. Map, select, collect, reduce/inject are pretty powerful
things and reduce code a lot. That said, it's important to get it
correct first, then refactor.
···
On Wed, Feb 6, 2013 at 7:25 PM, Tom Stut <lists@ruby-forum.com> wrote: