On Thu, Oct 4, 2012 at 6:09 PM, Jan E. <[email protected]> wrote:

> So this cannot work. You either have to split the string at the "-" or
> look for numbers with a regex:
>
> input = '1-3-11-7-4-7'
> players = input.split('-').map {|num| h[num.to_i]}
> p players
>
> or
>
> input = '1-3-11-7-4-7'
> players = input.scan(/\d+/).map {|num| h[num.to_i]}
> p players
>
> I didn't exactly understand what you want, so this is just an array of
> the selected values of the "h" hash.

I think OP wants to map numbers to names.  Since keys in this case are
numbers and they are in a relatively small range we can also use an
Array instead a Hash.  But first with a Hash:

h defined as above

irb(main):014:0> input = '1-3-11-7-4-7'
=> "1-3-11-7-4-7"

irb(main):016:0> input.scan(/\d+/).map {|n| h[n.to_i]}
=> ["p1", "p3", "p11", "p7", "p4", "p7"]
irb(main):017:0> input.scan(/\d+/).map {|n| h[Integer(n)]}
=> ["p1", "p3", "p11", "p7", "p4", "p7"]

now with an Array

irb(main):019:0> h=%w{p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11}
=> ["p0", "p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11"]
irb(main):020:0> input.scan(/\d+/).map {|n| h[Integer(n)]}
=> ["p1", "p3", "p11", "p7", "p4", "p7"]

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to