Can someone explain the following code to me?

前端 未结 5 1733
故里飘歌
故里飘歌 2021-01-20 05:59

I am following along with the Rails 3 in Action book, and it is talking about override to_s in the model. The code is the following:

def to_s
           


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 06:31

    It's string interpolation. "#{email} (#{admin? ? "Admin" : "User"})" is equivalent to

    email.to_s + " (" + (admin? ? "Admin" : "User") + ")"
    

    that is

    email.to_s + " (" + if admin? then "Admin" else "User" end + ")"
    

    As a result of being enclosed in quotes, in this context Admin and User are used as strings and not as constants.

提交回复
热议问题