On 1 June 2010 15:44, Matt Royer <lists@ruby-forum.com> wrote:
> I found the following topic in the forum:
> http://www.ruby-forum.com/topic/82137
>
> Ian J Cottee had an easy way of adding leading zeros to a number:
>
> ----
>
> "%05d" % an_int
>
> ----
>
> I'm still new to ruby, so I wanted to know. How would I put this into a
> method that I can attach to whatever string I wanted.
>
> I have the following in the view of my Rails app:
>
> ----
>
> "#{order.id} #{order.name}"
>
> ----
>
> I want to be able to create a method that will add the leading zeros to
> the order.id part. I know I'll have to do something like:
>
> "#{order.id}".leading_zeros + "#{order.name}"
>
> I know how to create a method. I just don't know how to put that code
> ("%05d" % an_int) into the leading_zeros method and be able to attach it
> to things.
Rather than attempt to add a method to the String class, which is what
you seem to be suggesting, You could add a method to your model that
returns the id and name as a formatted string. So in order.rb
something like
def order_code
"#{'%05d' % id} #{name}"
end
Then in the view just use
<%= @order.order_code %>
Colin
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment