Reputation: 401
I just started with Ruby recently and I'm hoping there is a shorthand for using a bound method as a proc I'm missing. I'm trying to do this essentially
SYMBOLS = {"I" => 1, "V" => 5, "X" => 10, ... }
roman = "zXXIV".upcase.chars.collect { |c| SYMBOLS[c] }
=> [nil, 10, 10, 1, 5]
I feel like there should be an easy way in ruby to just use SYMBOLS[] as a bound method, so just
roman = str.upcase.chars.collect &:SYMBOLS[]
Solution Ruby 1.9.3
roman = SYMBOLS.values_at(*str.upcase.chars)
Upvotes: 1
Views: 3120
Reputation: 160211
SYMBOLS.values_at(str.upcase.chars.to_a)
Regarding using SYMBOLS[]
, you'd still need to pass the character to the method.
You can get the method via SYMBOLS.method(:[])
, e.g.,
> p = SYMBOLS.method(:[])
> p.call("X")
=> 10
I'm not convinced it's the most readable in this case–for me, calling map
and passing in SYMBOLS[]
, while concise and functional, delays understanding what's happening longer than I prefer.
Upvotes: 2
Reputation: 303261
SYMBOLS = {"I" => 1, "V" => 5, "X" => 10 }
roman = "zXXIV"
p roman.chars.map(&SYMBOLS.method(:[]))
#=> [nil, 10, 10, 1, 5]
Upvotes: 2