What is the purpose of “!” and “?” at the end of method names?

后端 未结 5 2069
生来不讨喜
生来不讨喜 2020-12-04 07:28

Sometimes I see methods in Ruby that have \"?\" and \"!\" at the end of them, e.g:

name = \"sample_string\"
name.reverse
name.reverse!
name.is_binary_data?
<         


        
5条回答
  •  Happy的楠姐
    2020-12-04 07:42

    Beware, this isn't always the case. Take for example, Ruby Array#concat http://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-concat.

    Where you can get burnt badly is something like MyActiveRecordModel.column_names.concat([url]). Later calls related to MyActiveRecordModel will try to look for a column of 'url' for MyActiveRecordModel and throw.

    Instead you must clone it before doing the concat. Fortunately my test suite caught this one, but.. heads up!

提交回复
热议问题