Can someone explain the following code to me?

2020-04-10 01:34发布

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
  "#{email} (#{admin? ? "Admin" : "User"})"
end

I know that in Ruby you can display a value inside double quotes by the "#{value}", but what's up with the double question marks?

5条回答
不美不萌又怎样
2楼-- · 2020-04-10 01:59

This function is returning a string with the email and whether it they are an admin or user... ie

user_1 = {:email => "test@email.com", :admin => true}

so the call

user_1.to_s 

would return the string

"test@email.com Admin"
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-10 02:00

Actually admin? is a function(probably defined somewhere in controller/helper method or model) that return boolean(true or false) and next question mark is just like a if condition

if admin? == true
 "Admin"
else
 "User"

first portion before ":" is for true case and other is for false case

查看更多
Root(大扎)
4楼-- · 2020-04-10 02:02

Don't see it as a double question mark, the first question mark is part of the method name (Ruby allows methods name to end with "!", "?", "=", "[]", etc). Since admin is a boolean value ActiveRecord add an admin? method that returns true if the user is an admin, false otherwise.

The other question mark is used with the colon (:) and you can see it like:

condition ? statement_1 : statement_2

If condition is true the first statement is executed, else the second one it evalueted.

So put these two things together and you have a string concatenation that add the "Admin" or "User" word between parenthesis.

查看更多
我想做一个坏孩纸
5楼-- · 2020-04-10 02:09

The first question mark is attribute query methods in rails. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Attribute+query+methods

(provided you did not overwrite / redefine that method)

It is a shorthand method to see if that attribute present or not.

查看更多
Rolldiameter
6楼-- · 2020-04-10 02:14

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.

查看更多
登录 后发表回答