Skip to content

Instantly share code, notes, and snippets.

@SyunWatanabe
Last active February 16, 2020 05:27
Show Gist options
  • Select an option

  • Save SyunWatanabe/151963e289292d82a02735c6ac1537c1 to your computer and use it in GitHub Desktop.

Select an option

Save SyunWatanabe/151963e289292d82a02735c6ac1537c1 to your computer and use it in GitHub Desktop.
# Moduleを使う DeepFreeze(自作)
module Freeze
def deep_freeze(object)
object.freeze
object.each do |element, value|
element.freeze
value&.freeze
end
end
end
class Team
# クラス構文の直下ではクラスメソッドしか呼び出せない
extend Freeze
COUNTRIES = deep_freeze(['Japan', 'US', 'India'])
end
# 配列自身と配列の要素全部がfreezeされている
puts Team::COUNTRIES.frozen? # => true
puts Team::COUNTRIES.all? { |country| country.frozen? } # => true
class Bank
# クラス構文の直下ではクラスメソッドしか呼び出せない
extend Freeze
CURRENCIES = deep_freeze({ 'Japan' => 'yen', 'US' => 'dollar', 'India' => 'rupee' })
end
# ハッシュ自身とハッシュの全要素(キーと値)がfreezeされている
puts Bank::CURRENCIES.frozen? # => true
puts Bank::CURRENCIES.all?{ |key, value| key.frozen? && value.frozen? } # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment