On Mon, Sep 20, 2010 at 11:59 AM, Abder-Rahman A.
[email protected] wrote:
}
}
That seems pretty weird Java code. A method named “setFile” with a
single argument is conventionally a setter and does not return
anything. However, it seems you intend to do much more here. I
assume you are aiming for something like
public static short[][] readFile(File fileName) throws IOException {
final FileReader fr = new FileReader();
fr.setFileName(fileName);
fr.readFile();
return fr.getData();
}
ReadFile rf = new ReadFile();
Java: new X();
=>
Ruby: X.new
Does the preceding Java code look like the follows in Ruby:
class ReadFile
def set_file(filename)
def initialize
end
end
end
No, as others have explained already. There are some differences
between Ruby and Java. First and foremost Ruby does not have
overloading of method names with different argument lists so you
always ever have at most one #initialize per class and per module. If
you want to differentiate according to arguments you need to do it
yourself.
Then, in Java “new” is an operator while in Ruby it’s just an instance
method of class Class:
irb(main):001:0> Class.instance_method :new
=> #<UnboundMethod: Class#new>
You usually never fiddle with method #new but all you do is to provide
an implementation of #initialize. But in Ruby you can actually take
control over object allocation which is out of your control in Java.
For example, you can implement a singleton pattern like this:
irb(main):002:0> class Foo
irb(main):003:1> INSTANCE = allocate
irb(main):004:1> def self.new; INSTANCE; end
irb(main):005:1> end
=> nil
irb(main):006:0> f1 = Foo.new
=> #Foo:0x101a8484
irb(main):007:0> f2 = Foo.new
=> #Foo:0x101a8484
irb(main):008:0> [f1,f2].map {|f| Foo::INSTANCE.equal? f}
=> [true, true]
irb(main):009:0>
Note: you do not need to do this as there is module Singleton already
which does the job for you - although a bit differently.
Kind regards
robert