I am a seasoned developer with over 9 years of experience in Ruby on Rails and Golang. My passion lies in tackling complex data structures and algorithm problems, always pushing myself to learn and grow. In my downtime, I find solace in the pages of books and the soothing sounds of a guitar. But I'm not just a one-trick pony! I love to stay active and challenge myself in other ways too. Whether it's on the football pitch, cricket field, table tennis table, or badminton court, I'm always up for some fun activities.
1 minute read
Singleton classes are classes which can be instantiated only once.
There are various ways to create a singleton class or methods in Ruby as below:
Singleton class can also contain yield, which when called with a block will
execute the block. As shown below
Before Ruby 2.7 this function gets executed without any warnings or errors.
In Ruby 2.7
In Ruby 2.7 a warning will be issued when the above function is executed.
This will be deprecated since yield in singleton class syntax was inconsistent
with local variables accessibility.
Consider below example
The above code raises error as shown below
NameError (undefined local variable or method `x' for #<Class...>
NOTE: The variables declared in the block are accessible in the enclosing scope of
the singleton class.