Created
January 14, 2013 11:42
-
-
Save guilherme/4529531 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
# 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. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍