Created
October 17, 2011 08:24
-
-
Save maraigue/1292197 to your computer and use it in GitHub Desktop.
[Ruby] dup_if - dupできるオブジェクトは複製し、そうでなければselfを返すメソッド
This file contains 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 Object | |
def dup_if | |
begin | |
self.dup | |
rescue TypeError | |
self | |
end | |
end | |
def clone_if | |
begin | |
self.clone | |
rescue TypeError | |
self | |
end | |
end | |
def duplicable? | |
begin | |
self.dup | |
rescue TypeError | |
return false | |
end | |
true | |
end | |
def clonable? | |
begin | |
self.clone | |
rescue TypeError | |
return false | |
end | |
true | |
end | |
end | |
# 実行例 | |
if $0 == __FILE__ | |
x = "hoge" | |
y = x.dup_if | |
puts x.object_id == y.object_id # expected false | |
x = 42 | |
y = x.dup_if | |
puts x.object_id == y.object_id # expected true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment