Last active
August 29, 2015 14:13
-
-
Save kyuden/09c24de611740bc5b490 to your computer and use it in GitHub Desktop.
定数フリーズまとめ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
typo is frozen so we can't fix them
Yes, I can.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍
BTW,
s/premiam/premium/g
?