Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created October 17, 2011 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/1292197 to your computer and use it in GitHub Desktop.
Save maraigue/1292197 to your computer and use it in GitHub Desktop.
[Ruby] dup_if - dupできるオブジェクトは複製し、そうでなければselfを返すメソッド
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