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
此代码应打印"是"在屏幕上,但它没有。我将==符号更改为!=并且令人惊讶的是它打印了#34;是" ! 我想可能是我理解正则表达式错了所以我输入了这段代码:
puts my_dungeon.player.location.to_s.scan(/\D+/)
它打印" jail"在屏幕上,这意味着我没有错,是吗? 有人可以解释一下吗?
答案 0 :(得分:0)
正如Wiktor的评论所说,数组总是很简洁,scan
总是返回一个数组,即使没有匹配。相反,您可以使用以下任何一种方法:
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
通常,当您遇到类似这样的令人惊讶的行为时,您应该执行一些introspection - 检查使用print
或断点的结果值。