首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定义一个方法,该方法在接收对象大于参数对象ruby时返回true

定义一个方法,该方法在接收对象大于参数对象ruby时返回true
EN

Stack Overflow用户
提问于 2014-12-07 17:13:52
回答 1查看 252关注 0票数 1

我是一个ruby新手,正在做一个全栈的web开发人员课程@ Bloc.io,我在以下方面遇到了问题……

“我们应该能够对每个形状调用larger_than?方法。此方法应计算两个形状并根据一个形状的面积大于另一个形状的面积返回true或false。换句话说,如果接收对象大于参数对象,则larger_than?方法应返回true:

代码语言:javascript
复制
square.larger_than?(rectangle)

如果正方形大于矩形,则为true;否则为false

以下是规格:

代码语言:javascript
复制
describe "Shape" do
  describe "larger_than?" do
    it "should tell if a shape is larger than another shape" do
      class A < Shape
        def area
          5
        end
      end
      class B < Shape
        def area
          10
        end
      end
      a = A.new
      b = B.new
      expect( b.larger_than?(a) ).to eq(true)
      expect( a.larger_than?(b) ).to eq(false)
    end
  end

This is my code:

class Shape
  attr_accessor :color

  def initialize(color = nil)
    @color = color || 'Red'
  end

  def larger_than?
    if Shape.new.area > self.class.area
      true
    else
      false
    end
  end
end

class Rectangle < Shape
  attr_accessor :width, :height

  def initialize(width, height, color = nil)
    @width, @height = width, height
    super(color) 
  end

  def area
    width * height
  end
end

class Square < Rectangle
  def initialize(side, color = nil)
    super(side, side, color)
  end
end

class Circle < Shape
  attr_accessor :radius

  def initialize(radius, color = nil)
    @radius = radius
    super(color) 
  end

  def area
    Math::PI * (radius * radius)
  end
end

错误:

代码语言:javascript
复制
ArgumentError
wrong number of arguments (1 for 0)
exercise.rb:8:in `larger_than?'

exercise_spec.rb:18:in `block (3 levels) in <top (required)>'

我真的很感谢大家对我的遗漏/错误之处的反馈。

EN

回答 1

Stack Overflow用户

发布于 2014-12-07 17:37:18

免责声明:我试着不给你解决方案,而是提示你自己去获取解决方案。

除了larger_than?方法之外,您的代码看起来很不错。再想想这个方法是如何调用的:

代码语言:javascript
复制
square.larger_than?(rectangle)

它是在一个Shape对象上调用的,第一个参数是另一个Shape对象。

因此,该方法需要一个参数(另一个形状)。在该方法中,可以使用self访问当前形状,并使用另一个形状(使用参数)来比较这两个区域。

还有一件小事:你正在做这个:

代码语言:javascript
复制
if Shape.new.area > self.class.area
  true
else
  false
end

if语句中的测试表达式已经返回了一个Boolean (第一种情况下为true,第二种情况下为false )。因此,您可以直接返回测试表达式的值,而不是编写if语句。

更新

larger_than?方法应如下所示:

代码语言:javascript
复制
def larger_than?(otherShape)
  self.area > otherShape.area
end

self是调用larger_than?方法的形状。要比较这两个形状,必须比较这两个形状的面积。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27341240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档