Skip to content

Commit

Permalink
Merge pull request #649 from goby-lang/fix#647
Browse files Browse the repository at this point in the history
Add Integer#to_d
  • Loading branch information
st0012 authored Apr 15, 2018
2 parents 71edf12 + 22e5789 commit 583fecb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions vm/integer.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,24 @@ func builtinIntegerInstanceMethods() []*BuiltinMethodObject {
}
},
},
// Returns the `Decimal` conversion of self.
//
// ```Ruby
// 100.to_d # => '100'.to_d
// ```
// @return [Decimal]
{
Name: "to_d",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) > 0 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 arguments. got: %d", len(args))
}
r := receiver.(*IntegerObject)
return t.vm.initDecimalObject(intToDecimal(r))
}
},
},
// Returns the `Float` conversion of self.
//
// ```Ruby
Expand Down
23 changes: 23 additions & 0 deletions vm/integer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,17 @@ func TestIntegerConversion(t *testing.T) {
expected interface{}
}{
{`100.to_i`, 100},
{`-100.to_i`, -100},
{`100.to_f`, 100.0},
{`-100.to_f`, -100.0},
{`100.to_s`, "100"},
{`100.to_d.to_i`, 100},
{`-100.to_d.to_i`, -100},
{`100.to_d.numerator.to_i`, 100},
{`100.to_d.denominator.to_i`, 1},
{`-100.to_d.numerator.to_i`, -100},
{`-100.to_d.denominator.to_i`, 1},
{`100.to_d.class.name`, "Decimal"},
}

for i, tt := range tests {
Expand All @@ -236,6 +245,20 @@ func TestIntegerConversion(t *testing.T) {
}
}

func TestIntegerConversonFail(t *testing.T) {
testsFail := []errorTestCase{
{`100.to_d 1`, "ArgumentError: Expect 0 arguments. got: 1", 1},
}

for i, tt := range testsFail {
v := initTestVM()
evaluated := v.testEval(t, tt.input, getFilename())
checkErrorMsg(t, i, evaluated, tt.expected)
v.checkCFP(t, i, tt.expectedCFP)
v.checkSP(t, i, 1)
}
}

// Method test

func TestIntegerEvenMethod(t *testing.T) {
Expand Down

0 comments on commit 583fecb

Please sign in to comment.