2016-06-28 211 views
0

新手问题,我尝试在ruby应用程序中尝试调试错误, 你可以看到它hereRuby:空字符串和空字符串有什么不同?

代码:

def self.default_url_options 
    options = {:protocol => Setting.protocol} 
    if Setting.host_name.to_s =~ /\A(https?\:\/\/)?(.+?)(\:(\d+))?(\/.+)?\z/i 
     host, port, prefix = $2, $4, $5 
     options.merge!({ 
     :host => host, :port => port, :script_name => prefix 
     }) 
    else 
     options[:host] = Setting.host_name 
    end 
    options 
    end 

如果我host, port, prefix = $2, $4, $5后添加日志记录:

host, port, prefix = $2, $4, $5 
    Rails.logger.error "!!!!!!! '#{host}', '#{port}', '#{prefix}'" 

我: !!!!!!! “hostname.net”,“”,“”

所以prefix是空的,但如果设置:script_name明确地'' 改变程序的行为,我得到预期的结果,在 换句话说:

:script_name => '' 

和空$5给出不同的结果。

  1. $5和空字符串有什么区别?
  2. 从ruby程序员的角度来看这个问题的正确解决方法是什么?
+1

空的'$ 5'是指'nil'? – Aleksey

回答

1

当没有匹配时,$5变成nil,而不是空字符串。您在记录器中看到的是nil.to_s,显然它是一个空字符串。

但是在options,nil和空字符串有不同的含义。 nil的意思是“没有港口集”,而空字符串表示“端口设置为空字符串”,造成不便,如:

#     ⇓⇓ here is empty port! 
http://example.com:/path 

这使得整个事情失败。