Gokul
Gokul

Reputation: 493

Ruby string comparision

When I try to use the rps_game_winner method (see below) in CodeAcademy Labs, it works fine with the following input:

> rps_game_winner([ ["Dave", "P"], ["Armando", "S"] ])
valid value: p
valid value: s
=> ["Armando", "S"]

> rps_game_winner([ ["Allen", "P"], ["Richard", "P"] ])[0]
valid value: p
valid value: p
=> "Allen"

When I submit it for autograder homework, it always fails with a NoSuchStrategyError.

Failure/Error: rps_game_winner([ ["Dave", "P"], ["Armando", "S"] ])[0].should eq("Armando"), "Incorrect Winner returned"
     NoSuchStrategyError:
       NoSuchStrategyError

Can someone please help? Thanks.

def rps_game_winner(game)
  raise WrongNumberOfPlayersError unless game.length == 2
  a1=[(game[0][1]).downcase]
  a2=[(game[1][1]).downcase]
  a3=a1.to_s
  a4=a2.to_s
  valid=["r","p","s"]

  if(valid.include?(a3))
    puts "valid value: "+a3
  else
    raise NoSuchStrategyError
  end

  if(valid.include?(a4))
    puts "valid value: "+a4
  else
    raise NoSuchStrategyError
  end

  if(win(a1, a2))
    return game[0]
  else
    if a1.eql?(a2)
      return game[0]
    else
      return game[1]
    end
  end

  return game[0] if a1.eql?(a2)
end

Upvotes: 2

Views: 191

Answers (1)

Jing Li
Jing Li

Reputation: 15116

First I have no context of your homework. But according to NoSuchStrategyError, of course it hited valid.include?(x).

The cause could be (I assume) different versions of Ruby (1.8 codeacademy Labs vs 1.9 autograder). Because Array#to_s behaves differently on 1.8(join) and 1.9(inspect).

a1=[(game[0][1]).downcase]
a2=[(game[1][1]).downcase]
a3=a1.to_s
a4=a2.to_s
valid=["r","p","s"]

In 1.8: a3 will be something like "s".

In 1.9: a3 will be something like "[\"s\"]".

Please check this link: Ruby 1.9 Array.to_s behaves differently?

To solve this:

  a1=game[0][1].downcase
  a2=game[1][1].downcase

remove a3 and a4, only compare a1 and a2 should be fine on both 1.8 and 1.9.

Apart from that, you can also remove some redundancy by doing(not related to your question):

  [a1, a2].each do |x|
    if valid.include?(x)
      puts "valid value: #{x}"
    else
      raise NoSuchStrategyError
    end
  end

Upvotes: 2

Related Questions