Forum: Ruby Sippet needed to convert from a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F7b23ca97e51ae89341a19548aa63467?d=identicon&s=25 Tom Reilly (Guest)
on 2006-01-07 00:22
(Received via mailing list)
Snippit needed

given some option variables

c1 = 0
c2 = 0
c3 = 0
c4 = 0

given a string (a set of pairs of options) which could be read from
MYSQL or a file

paramString =  '"c1" 0 "c3" 1 "c2" "y" "c4" "v"'

such that:

c1 = 0
c2 = "y"
c3 = 1
and c4 = "v"

at the end of the procedure.

I just can't figure out how to do this with RUBY.

Thanks

Tom Reilly
2dc2228d8db84b46bdd834b0515a26a1?d=identicon&s=25 Lyndon Samson (Guest)
on 2006-01-07 06:05
(Received via mailing list)
On 1/7/06, Tom Reilly <w3gat@nwlagardener.org> wrote:
> given a string (a set of pairs of options) which could be read from
> MYSQL or a file
>
> paramString =  '"c1" 0 "c3" 1 "c2" "y" "c4" "v"'
>
> such that:
>
> c1 = 0
> c2 = "y"
> c3 = 1
> and c4 = "v"


eval is your friend for these type of tasks.
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-01-07 08:08
(Received via mailing list)
On 1/6/06, Tom Reilly <w3gat@nwlagardener.org> wrote:
> MYSQL or a file
> at the end of the procedure.
>
> I just can't figure out how to do this with RUBY.
>

There's no way yet to "meta-programmatically" set local variables.  If
you're OK with instance variables, you could replace the code I'm
about to paste with calls to instance_variable_set.

Here's one way, using a Hash:

irb(main):001:0> require 'enumerator'
=> true
irb(main):002:0> params = "c1 0 c3 1 c2 y c4 v"
=> "c1 0 c3 1 c2 y c4 v"
irb(main):003:0> h = {}
=> {}
irb(main):004:0> params.split.each_slice(2) {|key, val| h[key] = val}
=> nil
irb(main):005:0> h
=> {"c1"=>"0", "c2"=>"y", "c3"=>"1", "c4"=>"v"}
irb(main):006:0>
F7b23ca97e51ae89341a19548aa63467?d=identicon&s=25 Tom Reilly (Guest)
on 2006-01-07 23:38
(Received via mailing list)
Lyndon Samson wrote:

>On 1/7/06, Tom Reilly <w3gat@nwlagardener.org> wrote:
>
>
Thanks for the help.  This is just what I needed to get unstuck.
This topic is locked and can not be replied to.