tags:

views:

34

answers:

3

I'm currently trying to figure out how to pass an index range as a string, but so far have not been having any luck. Here is an example of what I'm trying to do:

pos = %w{1 2..4}
values = %{x cat}
test_string = "This is a test with a string."

test_string[pos[1]] = values[1]

I know I could just break it down with split or something similar, but I would really like to know how to pass this value directly. I thought I could accomplish it with eval, but so far I have been having no luck. Any help would be greatly appreciated, thanks!

A: 

not sure why you would want to do it this way, but you can do:

%Q{1 #{(2..4).to_a.join(' ')}}.split

NB: if your're trying to manipulate the test string you want pos[0].chr (arrays start at 0 and .chr will get the ASCII value).

EDIT: There has to be a better way to achieve what you're trying to do, give us some more information on what you need. something like the following might be sufficient:

[1] + (2..4).to_a

Edit2: With the info you've given try the following out

pos  = [15..22, 165..172] #array of ranges
dates = %w{20100426 20100430}
pos.each_with_index {|range, i| 
   test_string[range] = dates[i]
}
MatthewFord
I'm working with a fixed width file. There are certain fixed characteristics for the information contained in each position. I'm pulling positions from a config file and aligning them in an array at the same index position with what needs to be replaced.
Ruby Novice
can you give us a slimmed down example to work with, like an example config file and file with the replacements, I'm thinking a bunch of gsubs might be better for this
MatthewFord
Unfortunately, the config files contain information that I cannot give out. But an example would be that there are a number of years on each line of the fixed width file, always in the same positions. What I would do to update the years from a config file is place them into two arrays and replace the values that way.eg.position = %w{15..22 165..172}dates = %w {20100426 20100430 }I would like to do this so I can easily change characteristics in the config file without changing the code.
Ruby Novice
let me know how it goes with the code update, if you can keep the ranges in a ruby array it should work fine.
MatthewFord
Sorry for the delayed response, I actually solved it using this code yesterday:#test_string[pos[0].slice(/^\d+/).to_i..pos[0].slice(/\d+$/).to_i] = values[0]
Ruby Novice
A: 

The problem here is anything in %w gets converted to a string as-is. Try it in the console and you'll see this:

>> %w{1 2..4}
=> ["1", "2..4"]

It doesn't expand the range before converting it.

ryeguy
A: 

What you are trying to do, here? The indexes you are trying to use are strings not integers and hence invalid.
If you can explain where you are planning to get to, may be we can suggest an alternative route?

Hemant Kumar