4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyでJSの即時関数みたいなことをやる

Last updated at Posted at 2021-01-18

ちょっと例が悪いですが、自分用メモ。

↓こんなのがRubyで書きたかった。

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

別に普通に定義しても良いですが、処理部がごちゃごちゃしてくる場合は、変数の定義も処理部と切り離したいと思い、考えてみました。

class Hoge
  def initialize
    @root = root
  end

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

  private

  def root
    # pathへの代入は初期化の@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"

この例のrootメソッドで定義しているpathは直書きですが、なにかの処理結果をpathに格納して使いまわしたい場合は、何度も処理を走らせる必要がないので、いい感じ。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?