Post AJ73QLMsNV2AmqvfUW by andy_twosticks@ruby.social
(DIR) More posts by andy_twosticks@ruby.social
(DIR) Post #AJ73QJ3exyTTcfvIGG by postmodern@ruby.social
2022-05-03T23:50:23Z
0 likes, 0 repeats
I wish Ruby had a Hash#& method. I just need to quickly figure out the intersection of these two Hashes so I can push common data down into a common class.
(DIR) Post #AJ73QJUxKUJCzKh5o8 by andy_twosticks@ruby.social
2022-05-04T07:35:41Z
0 likes, 0 repeats
@postmodern Woke up and immediately thought I knew how to do this. stupidly posted nonsense. Never toot before you are awake.Now I've had coffee, I'm not even sure what you need. keys and values the same? Or just keys, in which case, what do you want to do in case of a conflict of values?It seems as if something along the lines of ´hasha.select{|k,v| hashb.has_key?(k) …´ would be the best solution, because it would spell out the answers to those questions…
(DIR) Post #AJ73QKAmoxll54GV0a by postmodern@ruby.social
2022-05-04T08:08:38Z
0 likes, 0 repeats
@andy_twosticks equivalent keys and values from both hashes. I ended up writing a small monkey patch in irb:class Hash def &(other) intersection = {} each do |key,value| if other[key] == value intersection[key] = value end end endend
(DIR) Post #AJ73QKkweWh0tDBNMu by andy_twosticks@ruby.social
2022-05-04T08:25:10Z
0 likes, 0 repeats
@postmodern hasha.select{|k,v| hashb[k] == v}
(DIR) Post #AJ73QLMsNV2AmqvfUW by andy_twosticks@ruby.social
2022-05-04T09:15:57Z
0 likes, 0 repeats
@postmodern Uh, reading that back, there's a gotcha that will catch your monkey patch and my select. if hashb[:foo] doesn't exist, you get null, which is falsy. If hasha[:foo] contains false … oops.Should be something like ´hasha.select{|k,v| hashb[k] && hashb[k] == v}´ -- I think?
(DIR) Post #AJ73QLuCNbgmSCWHQm by james@ruby.social
2022-05-04T15:33:56Z
0 likes, 0 repeats
@andy_twosticks @postmodern you also probably want to avoid using `hashb[k]` in a boolean expression in case the actual value is `false` 😄For example:hasha = {a: true, b: false}hashb = {b: false, c: true}hasha.select { |k,v| hashb[k] && hashb[k] == v }# => {}, but it should be {b: false}Instead, I'd suggest using `fetch`:hasha.select { |k,v| hashb.fetch(k) == v rescue false }
(DIR) Post #AJ75mRtL0J6bIZmUee by andy_twosticks@ruby.social
2022-05-04T16:00:24Z
0 likes, 0 repeats
@james @postmodern Fetch will raise an exception if the key is missing. No need for this. Just explicitly check if hashb[k] is null.
(DIR) Post #AJ761L3WhWgaRSeABE by james@ruby.social
2022-05-04T16:03:05Z
0 likes, 0 repeats
@andy_twosticks @postmodern I did consider that, e.g.hasha.select { |k,v| hashb.has_key?(k) && hashb[k] == v }I think they're about as nice as each other, I don't mind an incline `rescue`.The main gotchas to avoid with `[]` are making sure you don't accidentally get a default value, but `has_key?` should avoid that 👍️