Project

General

Profile

Actions

Bug #12875

closed

Fixnum bit operator and coerce

Added by lionel_perrin (Lionel PERRIN) about 8 years ago. Updated about 8 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
[ruby-core:77783]

Description

The following code raises "Test can't be coerced into Fixnum (TypeError)"

class Test
  attr_accessor :value
  def initialize(value)
    @value = value
  end
  def |(other)
    case(other)
    when Test
      @value | other.value
    else
      @value | other
    end
  end
  def coerce(other)
    [Test.new(other), self]
  end
end

1 | Test.new(2)

whereas the following works fine

class Test
  attr_accessor :value
  def initialize(value)
    @value = value
  end
  def +(other)
    case(other)
    when Test
      @value + other.value
    else
      @value + other
    end
  end
  def coerce(other)
    [Test.new(other), self]
  end
end

1 + Test.new(2)

It looks to me that the implementation of bit_coerce in numeric.c is not correct:

static int
bit_coerce(VALUE *x, VALUE *y)
{
    if (!RB_INTEGER_TYPE_P(*y)) {
	VALUE orig = *x;
	do_coerce(x, y, TRUE);
	if (!RB_INTEGER_TYPE_P(*x) && !RB_INTEGER_TYPE_P(*y)) {
	    coerce_failed(orig, *y);
	}
    }
    return TRUE;
}

My feeling is that it should be fine for the coerce method to return something else than integers, as long as the bit operator is implemented on the first element of the array.
For instance, in my case, it returns two Test instances and the operator '|' is correctly defined on Test instances. It should try this operator.

Regards,

Lionel

Updated by lionel_perrin (Lionel PERRIN) about 8 years ago

  • Description updated (diff)
Actions #2

Updated by nobu (Nobuyoshi Nakada) about 8 years ago

  • Status changed from Open to Closed

Applied in changeset r56543.


numeric.c: bit op with non-integer

  • numeric.c (rb_num_coerce_bit): enable bit operations with
    coercing by non-integer object. [ruby-core:77783] [Bug #12875]
Actions

Also available in: Atom PDF

Like0
Like0Like0