From: Robert Klemme Date: 2011-08-31T22:50:52+09:00 Subject: Re: Prepend a character to a string in ruby On Wed, Aug 31, 2011 at 1:00 PM, ruby rails wrote: > I am trying to insert a character to a string at the beginning of a > string. How is it possible in ruby. > I tried using >    s.times do |s| >    @space_availability+="0" >      end > But this would add at the end of the string. > The @space_availability is a string with 1's and 0's. I need to add 0's > at the beginning of this string. > I am a newbie in ruby You can use String#rjust irb(main):023:0> @space_availability = 'x' => "x" irb(main):024:0> @space_availability = @space_availability.rjust 5, '0' => "0000x" However, chances are that you want printf, sprintf or % operator. For example irb(main):013:0> sprintf '%0*d', 10, 8 => "0000000008" So, for numbers @space_availability = sprintf '%0*d', s, int_value If you want the string to represent a binary number you can do irb(main):015:0> sprintf '%0*b', 8, 123 => "01111011" Note, the '*' in the format string indicates there is an argument indicating the length before the value. If the length is fixed you can replace '*' with the length: irb(main):016:0> sprintf '%08b', 8, 123 => "00001000" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/