2012-02-17 5 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","") 

뭐죠 내 코드에 문제가? nil 인 경우 href의 기본값을 설정하려고합니다.

접견,

피터

답변

1

문제는 당신은 조건으로 .nil? or .empty?을 사용해야 여기

>> "".nil? 
=> false 

입니다.

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

,이 두 가지 작동합니다 :'LINK_TO를 (" Google ", nil); link_to ("Google "," ") – farnoy

+0

차갑다. 그게 전부 야. – pkberlin

1

""! =

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

가 여기에 기본값을 설정하는 청소기 방법 전무 : 당신이 두 조건을 경우

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