If I have v=(1…99).to_a and I want to index the 20th to 30th elements,
this is simply v[20,10]. But if I have a list of indexes i=[9, 11, 35,
47, 48, 55, 58, 63, 92, 96] that I want, I can’t seem to find a simpler
way than i.map{|x|v[x]} which seem like an aweful lot of syntax just for
what is essentially “v[i]”. Is there an easier way to do this?
-jason
(If your answer is “in Ruby it is easy to change the way basic primitive
operate yourself and hose everybody else in the project”, then please
keep it to yourself… that answer is getting a little tiresome.)
If I have v=(1…99).to_a and I want to index the 20th to 30th elements,
this is simply v[20,10]. But if I have a list of indexes i=[9, 11, 35,
47, 48, 55, 58, 63, 92, 96] that I want, I can’t seem to find a simpler
way than i.map{|x|v[x]} which seem like an aweful lot of syntax just for
what is essentially “v[i]”. Is there an easier way to do this?
array.values_at *i
-jason
(If your answer is “in Ruby it is easy to change the way basic primitive
operate yourself and hose everybody else in the project”, then please
keep it to yourself… that answer is getting a little tiresome.)
My answer is to
A) look over the documentation (ri Array, ri Array#values_at)
B) --And I mean this in the kindest way–stop thinking about how
things should be comparing to other languages and just go with the flow.
If I have v=(1…99).to_a and I want to index the 20th to 30th elements, this is simply v[20,10]. But if I have a list of indexes i=[9, 11, 35, 47, 48, 55, 58, 63, 92, 96] that I want, I can’t seem to find a simpler way than i.map{|x|v[x]} which seem like an aweful lot of syntax just for what is essentially “v[i]”. Is there an easier way to do this?
If I have v=(1…99).to_a and I want to index the 20th to 30th elements,
this is simply v[20,10]. But if I have a list of indexes i=[9, 11, 35, 47,
48, 55, 58, 63, 92, 96] that I want, I can’t seem to find a simpler way
than i.map{|x|v[x]} which seem like an aweful lot of syntax just for what
is essentially “v[i]”. Is there an easier way to do this?
v.values_at(*i)
(If your answer is “in Ruby it is easy to change the way basic primitive
operate yourself and hose everybody else in the project”, then please keep
it to yourself… that answer is getting a little tiresome.)
So tempting not to answer at all… or to tell you to RTFM…
Oh course. That’s (now) blindingly obvious. I don’t think there is much
I can do to prevent all the value_at calls. I can’t really lay out my
arrays differently to get better continuity, and I seem to be using
value_at almost every line where there is a decent amount of
computation. Overall, arbitrary indexing seems far more useful than
range based indexing using the [start,len] notation. After all, there is
already start…/…stop notation. Too bad I guess.