LoginSignup
12
11

More than 5 years have passed since last update.

ブロックの戻り値を返してくれるだけの書き方を考える

Last updated at Posted at 2015-02-02

あるオブジェクトを作りたい。
そのオブジェクトを作るには一時変数が必要だとする。

s1 = "pi"
s2 = "yo"
string = s1+s2 #=> "piyo"

とすると、中間結果s1,s2が残ってしまう。
そこで例えば、def below() yield endによって、

string = below do
  s1 = "pi"
  s2 = "yo"
  s1 + s2
end #=> "piyo"

みたいな感じで書きたい。

このdef below() yield endと同じことする書き方が、ググれど意外にも見つからなくて、悩んでるというお話です。
標準の範囲内で、良い書き方を募集しております。

追記

yancya さんの
手続きオブジェクトを作ってそのまま実行する書き方である
-> { .. }[]が良いと思いました。(たまに使わせてもらっています)

string = -> do
  s1 = "pi"
  s2 = "yo"
  s1 + s2
end[]
12
11
7

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
12
11