简体   繁体   中英

question mark, exclamation mark and select method in rails

http://jsfiddle.net/fidlesteex/xb10L4d3/

<% categories.select! {|x| !x.nil?} %>
<% end %>

may i have some clarification at the code above?

I have been studying at CA and it tends to fast track things. May i know where i could find more information about the script above? If i understand correctly, it kind of says execute everything inside the block as long as the "current" selected record is not null? the exclamation point is like a (this)? thanks for the replies!

No, this code runs the block for each element of categories and reject elements for which block returns falsy value from categories array. The block is { |x| !x.nil? } { |x| !x.nil? } { |x| !x.nil? } so it leaves only non-nil values in an array. Exclamation point and question mark at the end of the method name are actually parts of method name. Method name ending with exclamation point suggests that its usage can cause some side effects (like modification of original array in this case). Method name ending with question mark suggests that it returns boolean value.

The exclamation and question marks are common in Ruby methods. If you take chomp as example it has 2 variants - one with and one without the exclamation. The differences are:

hello = "Hello World\n"
x = hello.chomp
# x == "Hello World", hello == "Hello World\n"
hello.chomp!
# hello is now "Hello world"

So the variation with the exclamation has modified the original argument. They don't always mean the same thing though. In Rails for instance ActiveRecord has save and save! with the latter raising an exception when failing validation.

Question marks are used as they are in the English language; when asking a question. An example of this is the String start_with? . Best practice dictates that methods suffixed with a question will return a Boolean.

In your example, you're using Array.select! to keep all entries where the block returns true, consider another example, again using start_with :

x = ['hello', 'goodbye', 'hell']
x.select! do |str|
  str.start_with? 'hell'
end

x now is ['hello', 'hell'] , because we've used select! instead of select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM