Forum: Ruby on Rails erb Regex ?

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.
Chas C. (Guest)
on 2006-06-06 19:25
Hi

Got a column named 'sku' in a table named 'product'
<%= product.sku %>

...looks like this.... '1234_56'

These last two chars (56) are an audio Track number.
I ultimately want to display:
Track  <%= product.sku %>

I can isolate the first part with      /\d+\_/    = 1234_

But can't figure out how to get the last two chars ...... 56

Can someone point me to a source for that shows how to parse strings
like this in a Rails context?

THX

Chas
Wouter (Guest)
on 2006-06-06 21:01
/\_(.+)/ should give you the latest two chars.. If you need those
numbers a lot, I would make a method in your model.. something like:

def track()
  @sku =~ /\_(.+)/
  $1
end
Chas C. (Guest)
on 2006-06-07 00:24
Many thanks!!!


Wouter wrote:
> /\_(.+)/ should give you the latest two chars.. If you need those
> numbers a lot, I would make a method in your model.. something like:
>
> def track()
>   @sku =~ /\_(.+)/
>   $1
> end
Calle D. (Guest)
on 2006-06-07 14:55
(Received via mailing list)
>>>>> "Chas" == Chas C. <removed_email_address@domain.invalid> writes:

> Can someone point me to a source for that shows how to parse strings
> like this in a Rails context?

http://www.oreilly.com/catalog/regex2/index.html

--
		     Calle D. <removed_email_address@domain.invalid>
		 http://www.livejournal.com/users/cdybedahl/
    "Ah, optimism. I remember optimism." -- Anya, Buffy the Vampire
Slayer
Chas C. (Guest)
on 2006-06-07 23:02
Thanks Calle, I'm on it.....

Wouter.....Could you help me understand this one?
How do i call this def track() method?

So here is what I think is going on:

the (object) "product"
has an (attribute) "sku" which happens to have a value associated with
"sku" of 'xxxx_xx'

so every time rails finds and displays all these attributes, I want to
call:

def Track() in the store_controller.rb - run the method and return the
regexed value into the display.

But i just don't "get" how to associate the block with def Track....



in the store_controller.rb

  def track()
 @sku =~ /\_(.+)/
 $1
   end

in my store/index.rhtml

<% product.sku.track do |sku| %> <br/>
Track <%=  $1 %>
	<% end %>


Thanks for your indulgence!
Chas
Chas C. (Guest)
on 2006-06-08 06:10
well...I got it a different way.

seven characters in a string (ie. '0123_56')- I needed the last two as a
audio "Track" reference.

this works in place without a method or regex component

Track <%= product.sku[-2,2] %>   #     -2 says "start at the right, 2nd
place"  , 2 says "get 2 characters"

all is fine! now I just have to get only 1 character if the first is 0 -
'0123_02' - get 2 instead of 02
This topic is locked and can not be replied to.