Skip to content

Instantly share code, notes, and snippets.

@kyuden
Last active August 29, 2015 14:13
Show Gist options
  • Save kyuden/09c24de611740bc5b490 to your computer and use it in GitHub Desktop.
Save kyuden/09c24de611740bc5b490 to your computer and use it in GitHub Desktop.
定数フリーズまとめ
class MutableConstant
SERVICE_TYPES1 = ["basic", "premium", "pro"]
SERVICE_TYPES2 = ["basic", "premium", "pro"].freeze
SERVICE_TYPES3 = ["basic", "premium", "pro"].map(&:freeze).freeze
module Defaults
SERVICE_TYPES1 = ["basic", "premium", "pro"]
SERVICE_TYPES2 = ["basic", "premium", "pro"].freeze
SERVICE_TYPES3 = ["basic", "premium", "pro"].map(&:freeze).freeze
end
Defaults.freeze
def sample1(types)
types.delete_if {|type| !type.nil? }
end
def sample2(types)
types.map {|type| type << "_mode" }
end
end
# 参照オブジェクトの書き換え
p MutableConstant.new.sample1(MutableConstant::SERVICE_TYPES1) #=> []
p MutableConstant.new.sample1(MutableConstant::SERVICE_TYPES2) #=> 12:in `delete_if': can't modify frozen Array (RuntimeError)
# 参照オブジェクトが保持するオブジェクトの書き換え
p MutableConstant.new.sample2(MutableConstant::SERVICE_TYPES2) #=> ["basic_mode", "premiam_mode", "pro_mode"]
p MutableConstant.new.sample2(MutableConstant::SERVICE_TYPES3) #=> 12:in `block in sample2': can't modify frozen String (RuntimeError)
# 定数の再定義
p MutableConstant::SERVICE_TYPES3 = 100 #=> 100 :22:in warning: already initialized constant MutableConstant::SERVICE_TYPES3
p MutableConstant::Defaults::SERVICE_TYPES3 = 100 #=> :31:in `<main>': can't modify frozen Module (RuntimeError)
@yoshihara
Copy link

👍

BTW, s/premiam/premium/g ?

@uu59
Copy link

uu59 commented Feb 2, 2015

typo is frozen so we can't fix them

@kyuden
Copy link
Author

kyuden commented Feb 2, 2015

Yes, I can.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment