ruby - Why does uniq! return nil if there are no duplicates -
i'm starting ruby , find following violation of "principle of least surprise". , is, quoting the documentation, uniq! "removes duplicate elements self. returns nil if no changes made (that is, no duplicates found)."
can explain this, seems counter-intuitive me? means rather being able write 1 line of code below appending .uniq! end first line, instead have write following 2 lines:
hooks = io.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/) hooks = hooks.uniq
or missing something, better way?
edit:
i understand uniq! modifies operand. here's problem illustrated better hope:
hooks = io.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/) puts hooks.length #50 puts hooks.uniq!.length #undefined method `length' nil:nilclass
i contend way uniq! works makes senseless , useless. sure in case pointed out append .uniq first line. later in same program pushing elements onto array inside of loop. then, under loop, i'd "de-dupe" array, dare not write 'hooks_tested.uniq!' because return nil; instead must write hooks_tested = hooks_tested.uniq
indeed contend particularly egregious mis-feature in known principle that, when devising method returns array, 1 should @ least return empty array, rather nil
this because uniq!
modifies self
, if uniq!
return value wouldn't able know whether change occurred in original object.
var = %w(green green yellow) if var.uniq! # array contained duplicate entries else # nothing changed end
in code can write
hooks = io.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/) hooks.uniq! # here hooks changed
if need return value of hook perhaps because it's last method statement do
def method hooks = io.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/) hooks.uniq end
or otherwise
def method hooks = io.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/) hooks.uniq! hooks end
Comments
Post a Comment