Why Ruby 1.9 Overrides !! =! ~?

There were two good reasons for Ruby 1.8 does not support some types of overload, such as ||/ or, &&/ and, !/ not, ?::

  • Short circuit semantics cannot be implemented using methods in Ruby without very large changes to the language.
  • Ruby is hard-coded to handle only niland falseas false in boolean contexts.

The first reason does not apply to !/ not, but the second still does. It doesn't look like you can enter your own types of objects like boolean using only !, but &&/ ||is still hardcoded. For other applications, the complementarity operator ~with &/ already exists |.

I can imagine that there is a lot of code, it is expected that !objwill be synonymous with obj ? false : trueand !!objwith obj ? true : false- I'm not even sure how the code has to deal with objects that evaluate true in a boolean context, but !for something not-false.

It doesn't seem like Ruby plans to implement support for other false values. Nothing in Ruby stdlib seems to undo !, so I haven't found any examples.

Do I have a really good use that I am missing?

+3
source share
1 answer

Self-answer. So far, I have found one sensible application. I can hack this to work in 1.9.2 with just a few lines:

describe "Mathematics" do
  it "2 + 2 != 5" do
    (2+2).should != 5
  end
end

Prior to 1.9.2 Ruby, this means:

describe "Mathematics" do
  it "2 + 2 != 5" do
    ((2+2).should == 5) ? false : true
  end
end

But as we remove the return value, we have no way to distinguish it == 5from != 5the Ruby query for the parsing tree. PositiveOperatorMatcher#==(5)just raise an exception ExpectationNotMetError, and it will be so. It seems that should !~ /pattern/, should !be_somethingetc. Also may work.

This is a slight improvement over (2+2).should_not == 5, but not very large. And there is no way to crack it further to get things like (2+2).should be_even or be_odd.

, Ruby . Ruby. , ?

, ! !=/!~ . !((2+2).should == 5) #== !. #== , ! , . , . ( , , !self - )

+1

Source: https://habr.com/ru/post/1757304/


All Articles