3 ms·
For whatever reason, Ruby allows method names ending with ? or !. AFAIK the general practice is to use ! for methods that perform a mutation in-place (e.g. list
by pluma 11y ago
For whatever reason, Ruby allows method names ending with ? or !. AFAIK the general practice is to use ! for methods that perform a mutation in-place (e.g. list.sort! would sort a list in place, list.sort would be expected to return a new list) and to use ? for methods that return a boolean (e.g. list.empty? would indicate whether the list is empty).
- cremno 11y agoRuby inherited this from Scheme (and I prefer empty? over isempty or emptyp or variations thereof). They return truthy or falsy values and not true or false (the is* macros/functions in C only guarantee zero and nonzero as return value either). >AFAIK the general practice is to use ! for methods that perform a mutation in-place The ! suffix is rather loosely defined as it just means the user should be cautious/the method might have "dangerous"/surprising behavior. Your description is usually correct but only when a non-suffixed version exists and not even then the behavior has to match your description. There are also a lot unsuffixed mutating methods. See also Kernel#exit vs. Kernel#exit! (immediate exist/exit handlers aren't called) or Tempfile#close vs. Tempfile#close! (close and unlink).
- dragonwriter 11y ago> AFAIK the general practice is to use ! for methods that perform a mutation in-place That's not quite the usual statement of the rule: ! is for methods where there exists a "dangerous" version and a "less dangerous" version, to denote the more dangerous version. A common example of that is methods where one version returns a copy of the original object with some modification applied and the other version modifies the original object in place, but IIRCT that's not the only distinction it is used for in the standard library and, more importantly, in-place mutations that aren't paired with a "return-a-modified-copy" method don't get the !.
- lsaferite 11y agoPlease define IIRCT as I cannot find what it's meant to mean.