2012-02-17 92 views
0

我會玩Ruby。Ruby中的變量

現在我有一個小問題,我無法解決。

代碼:

@href = "http://localhost:3000" 

def link(title, href) 

    if href.nil? 
    href = @href 
    else 
    href = href 
    end 

    output = "<a href=\"#{href}\">" 
    output << "#{title}" 
    output << "</a>" 

    puts output 

end 

alias link_to link 

link_to("Google","") 

什麼在我的代碼的問題? 我想爲href設置一個默認值,如果它是零。

映入眼簾,

彼得

回答

1

的問題是在這裏

>> "".nil? 
=> false 

您應該使用.nil? or .empty?作爲條件。

>> "".empty? 
=> true 
+0

如果你做兩個條件,這兩個都可以工作:'的link_to(」 Google「,無); link_to(」Google「,」「)' – farnoy 2012-02-17 18:47:30

+0

酷。那是修復 – pkberlin 2012-02-17 18:54:54

1

「」!=零

[10] pry(main)> link "xxx",nil 
<a href="http://localhost:3000">xxx</a> 
=> nil 
2

這裏的設置默認的清潔方式:

def link(title, href = 'http://localhost:3000') 
    # ... 
end