6
1

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 5 years have passed since last update.

俺でもわかるシリーズAdvent Calendar 2017

Day 8

俺でも分かるJavaScriptでよくやるアレ in Ruby

Last updated at Posted at 2017-12-07

JSでよく使うあの機能・文法をRubyで使うにはどうしたらええんや、と思ったのでそれっぽい似たものをまとめた。

setTimeoutで非同期処理っぽいやつ

JSの場合
setTimeout(() => {
  // do something
}, 0);

Threadを使えばよさそう

Thread.new { 
  # do something
}

Promise

promiseというgemを使うと簡単に書ける。

x = promise { 1 + 2 }
puts x # 3

ちなみにconcurrent-rubyというのもあり、こちらのほうが新しく、頻繁にメンテされている。
単なる遅延評価ではなくスレッドセーフなのが売りらしい。

require 'concurrent'

result = Concurrent::Promise.execute do
  1 + 2
end

p result.value # 3

ちなみにこっちだと、JSっぽいthenを使った実装もできる

require 'concurrent'

chained_result = Concurrent::Promise
  .new  { 10 }
  .then { |result| result + 10 }
  .then { |result| result + 5 }
  .execute

puts chained_result.value # 25

Promise.all

concurrent-rubyzipメソッドを使う。

require 'concurrent'

p1 = Concurrent::Promise.new { 10 }
p2 = Concurrent::Promise.new { 20 }
p3 = Concurrent::Promise.new { 30 }

results = Concurrent::Promise
  .zip(p1, p2, p3)
  .then { |v| v }

p results.value # [10, 20, 30]

変数に関数を代入

JSでよくやるこれ。

JSの場合
const func = function() {
  return 1 + 2;
}

console.log(func()); // 3

Procを使うとそれっぽくできる

x = Proc.new do
  1 + 2
end
puts x.call # 3

これもよい!

x = ->{ 1 + 2 }
puts x.call # 3

即時関数

上で出てきたProcをすぐに呼び出すパターン

result ||= ->{
  1 + 2
}.call

p result // 3

begin...endを使うパターン。この記事によるとこちらのほうが速いらしい。

result ||= begin
  1 + 2
end

p result # 3
6
1
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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?