JeffD
JeffD

Reputation: 71

How to substitute integers with letters in Ruby

I am new to Ruby and programming. I am working on a card game. I have a variable (straightHigh) currently filled with a number n representing a rank of a card. I want certain numbers (11-14) to be replaced with specific letters (11 => J, 12 => Q, 13 => K, 14 => A).

I've tried gsub and gsub! with and without regular expressions. But regular expressions are very foreign to me.

if y == 5
  straightHigh = n + 4

  @straightHigh.to_s.gsub!(/[11-14]/, 11 => 'J', 12 => 'Q', 13 => 'k', 14 => 'A')
  p straightHigh.to_s

end

I've tried:

straightHigh.to_s.gsub!(/[11-14]/, 14 => 'Ace', 13 => K, 12 => Q, 11 => J)

which resulted in syntax errors.

I've tried

straightHigh.to_s.gsub!(/[11-14]/, 'Ace')

this does not throw an error, but does not seem to alter the values either.

Upvotes: 0

Views: 177

Answers (2)

Aaron Z
Aaron Z

Reputation: 358

I am not sure what you are trying to do, but I believe you are trying to map an integer with a string? If so, you can use a hash:

# straight_high Integer
# returns String
def get_card(straight_high)
  card_values = {
    11 => 'J',
    12 => 'Q',
    13 => 'K',
    14 => 'Ace',
  }

  card_values[straight_high]
end

Upvotes: 1

Léon Boutrand
Léon Boutrand

Reputation: 81

Maybe you should use a case statement:

def get_card(number)
  case number
  when 2..10
    return number.to_s
  when 11
   return 'J'
  when 12
   return 'Q'
  when 13
   return 'J'
  when 14
   return 'Ace'
  end
end

Upvotes: 2

Related Questions