Skip to content

Instantly share code, notes, and snippets.

@caius
Created September 13, 2010 22:12
Show Gist options
  • Save caius/578161 to your computer and use it in GitHub Desktop.
Save caius/578161 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.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
@ELLIOTTCABLE
Copy link

That’s what the fork function is for; more accurately, that’s what the edit function is for. No need to create a new one :O

As for the new intended operation… again, not exactly what the code probably intended, but interesting approach. Works fine if the obj is using accessors, which is probably an unsafe assumption… but it’s 4AM. :D

a .each {|k,v| obj.instance_variable_set(k, v) unless v.nil? }

@caius
Copy link
Author

caius commented Sep 14, 2010

Can't fork your own gists, so it was a toss up between editing it and making your comment outdated, or creating a new one and linking to it. Meh :)

And ew! Setting instance variables is a baaaad idea on an object you have no idea of the contents of. It could do any number of things in the setter methods (this is object-orientated code, it's fairly likely) that you'd bypass. If the setter does even set an instance variable! send("#{k}=", v) calls the setter and is much better from that respect.

@ELLIOTTCABLE
Copy link

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)

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