Do something like a JS immediate function in Ruby

A little bad example, but a personal note.

↓ I wanted to write something like this in Ruby.

const filepath = (() => {
  return "hoge/moge/huga";
})();

You can define it normally, but if the processing part gets messed up, I wanted to separate the variable definition from the processing part, so I thought about it.

class Hoge
  def initialize
    @root = root
  end

  def filepath(path)
    File.join(@root.call, path)
  end

  private

  def root
    #Assignment to path is initialization@Only when assigned to root
    path = "hoge/moge/huga"
    -> { path }
  end
end
 
hoge = Hoge.new

p hoge.filepath("a") # => "hoge/moge/huga/a"
p hoge.filepath("i") # => "hoge/moge/huga/i"
p hoge.filepath("u") # => "hoge/moge/huga/u"
p hoge.filepath("e") # => "hoge/moge/huga/e"
p hoge.filepath("o") # => "hoge/moge/huga/o"

The path defined in the root method of this example is written directly, but if you want to store some processing result in the path and reuse it, you do not need to run the processing many times. ,Good vibes.

Recommended Posts

Do something like a JS immediate function in Ruby
Implement something like a stack in Java
I want to do something like "cls" in Java
Multiplication in a Ruby array
About adding a like function
I wrote a C parser (like) using PEG in Ruby
Sorting hashes in a Ruby array
Add a search function in Rails.
I tried to write code like a type declaration in Ruby
Implement a gRPC client in Ruby
Implementation of like function in Java
I tried a calendar problem in Ruby
Do a prefix search in Swift's Firestore
Differences in writing in Ruby, PHP, Java, JS
Do not return when memoizing in Ruby
[Ruby on rails] Implementation of like function
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
Escape processing when creating a URL in Ruby
[Java] Create something like a product search API
[Ruby] I want to do a method jump!
I made a Ruby extension library in C
How to implement a like feature in Rails
(Ruby on Rails6) Creating data in a table
How to make a follow function in Rails
A certain programming classroom Ruby basic application function
Create a native extension of Ruby in Rust