【问题标题】:Get and Set Java into Ruby获取 Java 并将其设置为 Ruby
【发布时间】:2017-11-26 23:00:49
【问题描述】:
我目前正在学习 ruby 语言的 OOP,但我在理解构造函数概念时遇到了一些麻烦。所以我试图将我在java中做的一段代码转换成ruby。看看:
Java 代码:
public class Test {
public Test(int[][] array) {
this.array= array;
}
public int[][] getTest() {
return array;
}
}
Ruby 代码:
class Test
def Test(*array)
@test = test
end
def getTest()
return array
end
end
对吗?或者我应该使用初始化类?提前谢谢!
【问题讨论】:
标签:
java
ruby
class
parameters
constructor
【解决方案1】:
Java 代码:
public class Test {
private int[][] array; // you need to explicitly declare this
public Test(int[][] array) {
this.array = array;
}
public int[][] getTest() {
return array;
}
}
Ruby 代码:
class Test
#implicitly declares a getter method 'array' that returns @array field
attr_reader :array
# constructor. Test.new(array) to invoke
def initialize(*array)
@array = array # sets value to the private fiend @array
end
end
【解决方案2】:
问题是getTest 中的array 是一个局部变量。我有一种感觉,您想返回在test 方法中设置的变量(如果没有define_method,您不能将方法名称大写,但这是另一回事)。 Ruby 也为此提供了快捷方式。您可以使用以下几种方法:
class Test
attr_accessor :test
end
my_test = Test.new
my_test.test = "Hello Test"
my_test.test #=> "Hello Test"
以上示例使用内置的attr_accessor 方法为该变量定义一个setter 和一个getter 方法。
class Test
def test(value)
@test = value
end
def getTest
@test
end
end
这个和attr_accessor一模一样,但速度稍慢,getter方法重命名为getTest。
或者,如果您希望它成为构造函数:
class Test
def initialize(test)
@test = test
end
def getTest
@test
end
end
最后,如果你真的想要大写的方法名:
class Test
define_method(:Test) do |test|
@test = test
end
def getTest
@test
end
end