Skip to content

Instantly share code, notes, and snippets.

@caius
Created September 14, 2010 08:43
Show Gist options
  • Save caius/578741 to your computer and use it in GitHub Desktop.
Save caius/578741 to your computer and use it in GitHub Desktop.
# 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.one = a["one"] unless a["one"].nil?
obj.two = a["two"] unless a["two"].nil?
obj.three = a["three"] unless a["three"].nil?
obj.four = a["four"] unless a["four"].nil?
# "Best" (metaprogramming, ruby - fuck yeah!)
# %w() == Array
%w(one two three four).each do |key|
obj.send("#{key}=", 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