Re[2]: Proposing new warning

"Dan Fitzpatrick" <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <em80bd5082-737c-4639-abe3-d0a27c684a3c@carbonx>
I prefer the monkey patch to Hash in this case. String/Symbol keys on 
hashes is one of the only thinks I don't like about Ruby. So I "divide" 
my hashes by key with the "/" function:

Add this:

class Hash
   def /(k)
     self[k.to_sym] || self[k.to_s]
   end
end

Then you can do this:

h1 = {a: 1, b: 2}
h2 = {"c" => 1, "d" => 2}

The following returns 1:

h1/:a # 1
h2/:c # 1

x = 'a'
h1/x # 1

One issue is if you append another function you have to use parenthesis:

h = {now: Time.now}
h/:now.strftime('%Y%m%d')  #<= ERROR
(h/:now).strftime('%Y%m%d')  # "20181023"

This is my solution but it is considered hackery by many. The thing I 
like about it is that it is easy and I know that I am getting values by 
symbol or key and you can still do stuff like:

h = {a: 1, "a" => 2} and access the values as you normally would with 
h[:a] or h["a"]


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.