useranon
useranon

Reputation: 29514

String manipulation and concatenating in Ruby on rails

I have a String like:

"/system/path/513/b02/36a/66ea2557[*,0].swf,16"

I'm using Ruby on Rails for my application. I am trying to make 16 urls by appending 1-16 to the end of 66ea2557 to get something like:

"/system/path/513/b02/36a/66ea25571.swf"
"/system/path/513/b02/36a/66ea25572.swf"
..
"/system/path/513/b02/36a/66ea255715.swf"
"/system/path/513/b02/36a/66ea255716.swf"

How can I do this in Ruby?

Upvotes: 0

Views: 235

Answers (4)

Paul Fioravanti
Paul Fioravanti

Reputation: 16793

Assuming that:

  • You're given "/system/path/513/b02/36a/66ea2557[*,0].swf,16" from somewhere perhaps out of your control and it needs to be parsed
  • The number 16 at the end of the string won't necessarily be the same every time and signifies the number of urls you need
  • You don't need the [*,0] part of the string for anything and it doesn't necessarily signify anything

I came up with:

string = "/system/path/513/b02/36a/66ea2557[*,0].swf,16"
base_path, _, file_extension, num_urls = string.split(/(\[\*,0\])|,/)
# => ["/system/path/513/b02/36a/66ea2557", "[*,0]", ".swf", "16"]
(1..num_urls.to_i).map { |i| "#{base_path}#{i}#{file_extension}" }
# => ["/system/path/513/b02/36a/66ea25571.swf",
      "/system/path/513/b02/36a/66ea25572.swf",
      ...
      "/system/path/513/b02/36a/66ea255716.swf"]

Upvotes: 2

olistik
olistik

Reputation: 794

You could use String#%:

path = "/system/path/513/b02/36a/66ea2557%s.swf"
(1..16).map {|index| path % index}

Upvotes: 0

Roney Michael
Roney Michael

Reputation: 3994

You could try simple looping. Something like:

#test.rb

arr = Array.new();
for i in 1..16
    arr[i-1] = "/system/path/513/b02/36a/66ea2557" + i.to_s;
end

puts arr;

Upvotes: 0

Reck
Reck

Reputation: 8762

(1..16).each do |i|
  puts "/system/path/513/b02/36a/66ea2557#{i}.swf"
end

Upvotes: 0

Related Questions