2011-11-20 86 views
0

軌道有一個this像javascript/jquery嗎?軌道三元運算符和'這'

拿這個例子:

User.find_by_email(params[:candidate][:email].present? ? (u = this.id) : (u = 'not here') 

或:

if User.find_by_email(params[:candidate][:email].present? 
    a += 1 
    user = this 
end 

我知道,這個代碼可能會在這種情況下更有效的方式被改寫,但我的問題是關於是能夠使用this。 Ruby有這樣的東西嗎?

+3

'self'是Ruby的'this'。儘管你的代碼很混亂。 js中的 –

+1

,這是關於函數的上下文,而不是與操作符有關。 –

回答

3

在上課時您使用self

在這些情況下,雖然此代碼不在User上下文中,所以您必須進行分配。

u = User.find_by_email(params[:candidate][:email]) 

user_name = u.any? ? u.name : 'not here' 

我喜歡.any?.present?在這種情況下,因爲它讀取更好。

+0

'find_by_email'方法將返回一個對象或'nil'。 'any?'方法可以用於數組/散列枚舉器。你的代碼會拋出'NoMethodError'錯誤。我會使用'User.find_by_email(params [:candidate] [:email])。try(:name)|| '不在這裏'(假設'name'字段在用戶對象中永遠不會是空的)。 –

1

我猜你的情況下,更地道的紅寶石的辦法是類似以下內容:

User.where("email in (?)", email_arr).each do |user| 
    a += 1 
    user.foo = bar 
end 

但很難沒有看到的所有代碼的話。

2

Ruby使用self來表示this。我不太確定你是否需要使用self來解決你的問題。

第一種情形可以被改寫爲:

u = User.find_by_email(params[:candidate][:email]).try(:id) || 'not here' 

第二種情況可以改寫爲:

user = User.find_by_email(params[:candidate][:email]) 
a += 1 if user.present? 
+0

我只是寫了一些快速示例來試圖說明我正在學習的自我引用。這些例子不是偉大的代碼,我知道!謝謝。 – sscirrus

+0

@sscirrus不要猶豫,發佈代碼。我相信這裏有人能夠回答這個問題。 –