Tim Hunter wrote:
> Max Williams wrote:
>>   => "Copy 2 of My Lesson"
>> 
>> new_name("Copy 10 of My Lesson")
>>  => "Copy 11 of My Lesson"
>> 
>> I can only come up with horrible looking solutions but i feel there's a
>> nice way to do it.  Anyone?
>> 
>> cheers
>> max
> 
> Use a closure to keep track of how many copies you've made:
> 
> def copy(string)
>    x = 0
>    p = lambda do
>      x += 1
>      if x == 1
>        "Copy of #{string}"
>      else
>        "Copy #{x} of #{string}"
>      end
>    end
>    p
> end
> 
> c = copy("My Lesson")
> 
> puts c.call
> puts c.call
> puts c.call

That method returns a proc though, rather than a string.  Wouldn't that 
mean that every time i want to call it i have to assign it to a variable 
and then call that variable?  Or am i being dumb?  here's my 
hacky-feeling solution:

  def copied_name(source_name)
    if source_name.match /^Copy of/i
      new_name = source_name.gsub!(/^Copy of/i, "Copy 1 of")
    elsif source_name.match /^Copy \d+ of/i
      num = source_name.scan(/\d+/).first.to_i
      new_name = source_name.gsub!(/^Copy #{num} of/i, "Copy #{num+1} 
of")
    else
      new_name = "Copy of " + source_name
    end
  end

>> s = "My Lesson"
=> "My Lesson"
>> copied_name(_)
=> "Copy of My Lesson"
>> copied_name(_)
=> "Copy 1 of My Lesson"
>> copied_name(_)
=> "Copy 2 of My Lesson"


-- 
Posted via http://www.ruby-forum.com/.