Skip to content

Instantly share code, notes, and snippets.

@guilherme
Created January 14, 2013 11:42
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 guilherme/4529531 to your computer and use it in GitHub Desktop.
Save guilherme/4529531 to your computer and use it in GitHub Desktop.
# vamos supor:
def convert_to_f(argument = nil)
argument.tap do |attribute|
attribute = attribute.to_f if attribute
end
end
convert_to_f
# esperado: nil
# obtido: nil
convert_to_f("12345.6")
# esperado: 12345.6
# obtido: "12345.6"
# porque ?
# explicação:
def convert_to_f(argument = nil)
p '------- before tap --------'
p argument.object_id
ret = argument.tap do |arg|
p '------- inside tap --------'
arg = arg.to_f if arg
p arg.object_id
end
p '------- after tap --------'
p ret.object_id
ret
end
convert_to_f("12345.6")
"------- before tap --------"
70247576823060 <= equal
"------- inside tap --------"
70247576822540 <= different
"------- after tap --------"
70247576823060 <= equal
=> "12345.6"
# ou seja, é criado um objeto novo, o tap funciona quando você quer mudar um estado interno do objeto e não o objeto.
@douglasresende
Copy link

👍

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