[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Sippet needed to convert from a string

Tom Reilly

1/6/2006 11:22:00 PM

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



3 Answers

Lyndon Samson

1/7/2006 5:04:00 AM

0

On 1/7/06, Tom Reilly <w3gat@nwlagardener.org> wrote:
>
> 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"


eval is your friend for these type of tasks.

Wilson Bilkovich

1/7/2006 7:06:00 AM

0

On 1/6/06, Tom Reilly <w3gat@nwlagardener.org> wrote:
> 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.
>

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>


Tom Reilly

1/7/2006 10:38:00 PM

0

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.