2017-10-27 6 views
0
Player = Struct.new(:reference, :name, :state, :items, :location) 

# Setting game initials 
game_condition = 0 
player = Player.new(:player, "Amr Koritem", :alive, [:knife, :gun]) 
puts player.name 
player.location = :jail5 
class Dungeon 
    attr_accessor :player, :rooms, :prisoners, :gangsmen, :policemen 
    @@counter = 0 
    def initialize(player) 
     @player = player 
    end 
end 
my_dungeon = Dungeon.new(player) 
if my_dungeon.player.location.to_s.scan(/\D+/) == "jail" 
    puts "yes" 
end 

이 코드는 화면에 "예"라고 인쇄되지만 실제로는 인쇄되지 않습니다. 나는 == 표시를! =로 변경했으며 놀랍게도 "예"라고 인쇄했습니다! 나는 그래서이 코드 입력 잘못된 정규 표현식 이해 될 수있다 생각 : 화면에루비 : 정규 표현식의 논리

puts my_dungeon.player.location.to_s.scan(/\D+/) 

그것은 인쇄 "감옥"내가 잘못이 아니었다 의미, I이었다? 누구든지 설명해 주시겠습니까?

+2

'scan'은 배열을 반환합니다. 'my_dungeon.player.location.to_s [/ \ D + /] == "jail"'을 사용할 수 있습니다. 당신은'\ D +'이 당신에게 적합한 패턴이라고 확신합니까? 숫자가 아닌 하나 이상의 문자와 일치합니다. –

+0

예, 숫자를 원하지 않습니다. 나는'scan'이 문자열을 리턴한다고 생각했지만, 이제는 그것이 의미있는 배열을 리턴한다고 말했을 것이다. 해명 해줘서 고마워. –

답변

0

Wiktor의 의견에 따르면 배열은 항상 진실이며 scan은 일치하는 항목이 없더라도 항상 배열을 반환합니다. 대신 다음 방법 중 하나를 사용할 수 있습니다 : 당신은 당신이 introspection의 조금을해야이 같은 놀라운 행동을 건너 때 일반적으로

str = "jail5" 

if str[/\D+/] # => nil or the match contents 
if str.match /\D+/ # => nil or MatchData object 
if str =~ /\D+/ # => nil or index of the match 
unless str.scan(/\D+/).empty? 
if str.scan(/\D+/).length > 0 

를 - 결과 값이 print 또는 중단 점을 사용하는 것을 확인.

+1

일치해야합니다 (/ \ D + /)' – Max

+0

많은 감사합니다. 나는 다음 번에 그것을 시험해 볼 것입니다. –