Created
September 13, 2010 22:12
-
-
Save caius/578161 to your computer and use it in GitHub Desktop.
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
# if ([a valueForKey:@"key"] == [NSNull null]) | |
# obj.foo = [a valueForKey:@"key"]; | |
# Copied straight into ruby | |
if a["key"] != nil | |
obj.foo = a["key"] | |
end | |
# Use a ruby method to test for nil | |
if !a["key"].nil? | |
obj.foo = a["key"] | |
end | |
# "if !" == "unless" | |
unless a["key"].nil? | |
obj.foo = a["key"] | |
end | |
# "unless obj.nil?" == "if obj" if obj isn't going to be false | |
if a["key"] | |
obj.foo = a["key"] | |
end | |
# Why waste three lines when we can do it in one | |
obj.foo = a["key"] if a["key"] | |
# Or if we care about a["key"] being false too | |
obj.foo = a["key"] unless a["key"].nil? | |
# Ew. | |
unless a["one"].nil? | |
obj.one = a["one"] | |
end | |
unless a["two"].nil? | |
obj.one = a["two"] | |
end | |
unless a["three"].nil? | |
obj.one = a["three"] | |
end | |
unless a["four"].nil? | |
obj.one = a["four"] | |
end | |
# Better | |
obj.foo = a["one"] unless a["one"].nil? | |
obj.foo = a["two"] unless a["two"].nil? | |
obj.foo = a["three"] unless a["three"].nil? | |
obj.foo = a["four"] unless a["four"].nil? | |
# "Best" (metaprogramming, ruby - fuck yeah!) | |
# %w() == Array | |
%w(one two three four).each do |key| | |
obj.foo = a[key] unless a[key].nil? | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You totally can fork your own gists! cf. http://gist.github.com/579109
And yeah, like I said, it’s not what was intended by that particular bit of code; but I consider it far, far more attractive than
send
hackery.Unfortunately, it’s fairly ugly either way, mostly because Ruby’s object system sucks. (Objects aren’t just associative arrays, and I can’t just set any slot I want to any value I want, whenever I want? Man, and I used to like that object system! ashamed)