简体   繁体   中英

Ruby: Logic of regular expression

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

This code is supposed to print "yes" on the screen, but it doesn't. I changed the == sign to != and surprisingly it printed "yes" ! I thought may be I understood the regular expression wrong so I typed this code:

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

It prints "jail" on the screen, which means I wasn't wrong, was I ? Can anyone explain this please ?

As Wiktor's comment says, arrays are always truthy, and scan always returns an array, even if there are no matches. Instead you can use any of the following methods:

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

In general when you come across surprising behavior like this you should do a bit of introspection - check what the result value is using print or a breakpoint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM