On Mon, Sep 20, 2010 at 11:59 AM, Abder-Rahman Ali
<abder.rahman.ali / gmail.com> wrote:
> Like constructors in Java, I understood that in Ruby, we use
> "initialize" for this issue.
>
> If I have the following in Java:
>
> public class ReadFile
> {
> public static short[][] setFile(fileName)
> {
> ReadFile rf = new ReadFile();
> }
> }

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();
}

> Regarding:
>
> public static short[][] setFile(fileName)
>
> In a previous thread, I understood that I can represent it in ruby as:
>
> def set_file(filename)
> end
>
> But, now, as for:
>
> 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

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/