Do you think if my following code is correct for implementing a static
method (maybe singleton, or class method) in ruby class?
class Foo
@@x = 0
def self.count
@@x += 1
@@x
end
end
puts Foo.count
puts Foo.count
puts Foo.count
The run results:
$ ruby t1.rb
1
2
3
When to use instance methods or class methods, instance variables or
class variables, should be directly related to the semantic meaning
that you give to your classes. The class 'Foo' that I attach, for
example, is a factory of Foo instances that acquire their own
progressive ID. Thus, the one class variable that I define remembers
the latest assigned ID. 1, 2 and 3 are thus properties of the three
produced instances.
The run results:
$ ruby foo_factory.rb
I am Foo #1
I am Foo #2
I am Foo #3
How would you define Foo in your own example? (sorry but I cannot
compare scala code).
Carlo
···
Subject: [ruby-talk:443054] how to implement a static method in ruby class?
Date: Thu 13 Oct 22 04:00:52PM +0800
--
* Se la Strada e la sua Virtu' non fossero state messe da parte,
* K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe
* di parlare tanto di amore e di rettitudine? (Chuang-Tzu)
Enviado con Proton Mail correo electrónico seguro.
···
------- Original Message -------
El jueves, 13 de octubre de 2022 a las 13:15, Austin Ziegler <halostatue@gmail.com> escribió:
Avoid using class variables. They don’t quite work the way you think they do. They still have their place, but it’s exceedingly rare.
Prefer instance variables, remembering that classes are instances, too.
`ruby class Foo def self.count @count ||= 0 @count += 1 end end`
-a
> On Oct 13, 2022, at 04:01, Henrik P henrik@simplemail.co.in wrote:
>
> Do you think if my following code is correct for implementing a static method (maybe singleton, or class method) in ruby class?
>
> class Foo
> @@x = 0
>
> def self.count
> @@x += 1
> @@x
> end
> end
>
> puts Foo.count
> puts Foo.count
> puts Foo.count
>
> The run results:
>
> $ ruby t1.rb
> 1
> 2
> 3
>
> I want a method like this one in scala code.
>
> object Foo {
> var int = 0
> def increase = { int += 1; int }
> }
>
> println(Foo.increase)
> println(Foo.increase)
> println(Foo.increase)
>
> Thank you.
>
> --
> Simple Mail
> https://simplemail.co.in/
>
> Unsubscribe: mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe
> http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk