Feature #13290
closedA method to use a hash like in a case construction
Description
We often want to translate a hash into a case construction and back. For example, suppose we have a case construction like this:
case key
when /foo/ then "FOO"
when /bar/ then "BAR"
else "DEFAULT"
end
Given that the keys are ordered within a hash since Ruby 1.9, the information used in the case construction above can be expressed as a hash h
:
h = {
/foo/ => "FOO"
/bar/ => "BAR"
...
}
h.default = "DEFAULT"
At the moment, there is no straightforward way to translate the hash h
into the case construction as above. I would like to have a method on Hash
that takes a key and works like a case construction (i.e., applies the ===
method) as below:
h.fetch_as_in_case_construction("barbar") # => "BAR"
The name fetch_as_in_case_construction
is terrible. Perhaps someone can suggest a better name.
Updated by shevegen (Robert A. Heiler) about 7 years ago
I love case/when menus, so I am all for suggestions that make case/when more
useful, so I also support this (even if this one is indirect, on class Hash,
to have them behave like a case/when menu).
I also would like to see case/when become first-class citizens (objects) one day
that can also be merged together (e. g. unify two different case/when menus
together, both working on the same variable... a bit similar as to how hashes
can be merged together too. A bit like UnboundMethod where we could, in
theory, detach a method and attach it to another object or use another
environment ... but I digress again, sorry.)
The name "fetch_as_in_case_construction" is indeed a bit terrible,
I am glad that I am not the only one who suggests terrible names. :D
But I think the more important part is whether matz/ruby core team
think that the underlying functionality would be ok to be had.
Finding good names is hard but possible! I also have no really better
suggestion. My suggestions may even be worse ... such as :)
Obvious ones would be ".to_case" or, if the other way around, on
a first-class citizen case object, .to_hash. Or some method called
"convert" or "transform" or "treat_as_case" or ... I dunno.
But +1 anyway.
Updated by duerst (Martin Dürst) about 7 years ago
Tsuyoshi Sawada wrote:
The name
fetch_as_in_case_construction
is terrible. Perhaps someone can suggest a better name.
What about simplifying this to fetch_as_case
? Or maybe even just case
? Just thinking out loud.
Updated by mame (Yusuke Endoh) about 7 years ago
h.find {|a,| a === "barbar" }.last #=> "BAR"
This is good enough to me.
Updated by sawa (Tsuyoshi Sawada) about 7 years ago
Yusuke Endoh wrote:
h.find {|a,| a === "barbar" }.last #=> "BAR"
This is good enough to me.
I expected something that would be as easy as and comparable to h[key]
.
Updated by matz (Yukihiro Matsumoto) about 7 years ago
- Status changed from Open to Feedback
I don't see how mush useful this proposal is. Please show us concrete use-case.
Matz.