Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby类关联_Ruby_Oop_Associations - Fatal编程技术网

Ruby类关联

Ruby类关联,ruby,oop,associations,Ruby,Oop,Associations,我在Ruby中创建类关联时遇到问题,因为它是一种动态类型语言。在Java中,我这样写: public class Foo { ... } public class Bar { public Foo foo; ... } 我怎样才能用Ruby写类似的东西呢 class Foo end class Bar attr_accessor :foo def initialize (foo) @foo = foo end end foo = Foo.ne

我在Ruby中创建类关联时遇到问题,因为它是一种动态类型语言。在Java中,我这样写:

public class Foo {
   ...
}

public class Bar {
   public Foo foo;
   ...
}
我怎样才能用Ruby写类似的东西呢

class Foo

end

class Bar

  attr_accessor :foo

  def initialize (foo)
    @foo = foo
  end

end

foo = Foo.new
bar = Bar.new(foo)

puts bar.foo
对于你所说的,似乎你需要某种类型的安全。你可以通过这样做来实现

def initialize (foo)
  raise ArgumentError, "You must provide a valid Foo instance" unless foo.instace_of?(Foo)
  @foo = foo
end

我不太清楚。我想将一个现有的Foo对象传递给Bar。我相信您想在构造函数中传递它?编辑是的,没错。我已经考虑过这个解决方案,但对我来说似乎很危险,因为我可能会通过构造函数传递错误的变量。我想这是动态打字的价格。无论如何,谢谢你!那里我编辑了答案以提供某种类型的安全性。无论如何,在ruby中,最好不要关心类型,只要看看对象是否可以使用
respond\u to?
Hey from future来响应消息即可。这能让我拿到食物吧吗?或者只是巴富?