user2448377
user2448377

Reputation: 69

Undefined method '.any?' for "":String (NoMethodError

def room_actions    
  case $next_move
  when "instructions"
    instructions
  when $next_move.any? { |x| ['up', 'down', 'left', 'right'].include?(x) }
    determine_start
  else 
    puts "I don't understand that."
    prompt; $next_move = gets.chomp()
    room_actions
  end
end

Forgive me for not understanding what's going on here, but why is ruby throwing this error?

foo.rb:83:in room_actions': undefined methodany?' for "":String (NoMethodError)

$next_move is a global variable (I know they're bad, I'm refactoring) that I feed into this method from a gets chomp in a state machine.

It seems that I'm failing to define the 'any?' method. Or that the string I'm passing is empty? Anyway, isn't '.any?' a built in ruby method? I'm using 2.0.0.

Thank you for taking a look and advising.

Upvotes: 1

Views: 5292

Answers (3)

d0minikk
d0minikk

Reputation: 49

any? method is for arrays. do just: ['up', 'down', 'left', 'right'].include?($next_move)

Upvotes: 0

Patrick Oscity
Patrick Oscity

Reputation: 54684

The error message

undefined method `any?' for "":String

means you are trying to call any? on a String. The any? method, however, is only defined on Enumerable (and thus on collections like Array and Hash)

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84124

Strings (empty or not) don't have an any? method (enumerable such as arrays or hashes do. Strings were enumerable in ruby 1.8 but are no longer so).

It's very unclear to me why you are trying to call .any? on it in the first place - if you want to check whether it is one of that list of allowable values then

['up','down','left','right'].include?($next_move)

Will do the job

Upvotes: 5

Related Questions