简体   繁体   English

Ruby:正则表达式的逻辑

[英]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 ? 它在屏幕上打印“ jail”,这表示我没看错,是吗? 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. 正如Wiktor的评论所言,数组始终是真实的,即使没有匹配项, scan总是返回数组。 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. 通常,当您遇到这种令人惊讶的行为时,您应该进行一些自省 -检查使用print或breakpoint的结果值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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