Reversing a string without using array, classes and reverse function

R

Rubist Rohit

I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above line
in loop?
 
S

spiralofhope

I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above
line in loop?

Here's something I stumbled through which seems to work.

- Using a regex of /.$/
- Slowly chomping away at the original string.
- Using another variable to build my result.



mystring = 'Hello, World!'
result = ''

fail = 0
until fail == "100" or mystring == '' do
fail += 1
mystring.match( %r{(.$)} )
break if $~ == nil
result += $~[1]
mystring = mystring.chomp( $~[1] )
end

puts result
 
R

Rubist Rohit

I attempted below given code, but it is neither displaying result nor
error:

================CODE==========================
s = "This is to test reverse of a string"
len = s.length
for j in len..1 do
mycommand = "s.scan(/.$/) {|x| puts x}"
mycommand = mycommand.insert 7,"."
end
==============================================

What I am doing is to insert a period (.) in the seventh or eighth
position on each loop.


spiralofhope wrote in post #994433:
I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above
line in loop?

Here's something I stumbled through which seems to work.

- Using a regex of /.$/
- Slowly chomping away at the original string.
- Using another variable to build my result.

mystring = 'Hello, World!'
result = ''

fail = 0
until fail == "100" or mystring == '' do
fail += 1
mystring.match( %r{(.$)} )
break if $~ == nil
result += $~[1]
mystring = mystring.chomp( $~[1] )
end

puts result
 
J

Jose Calderon-Celis

[Note: parts of this message were removed to make it a legal post.]

#!/usr/bin/env ruby
#
require 'rubygems'

puts "ruby #{RUBY_VERSION}"
s = "This is to test reverse of a string"
p s
len=s.length
mycommand=""
for j in 1..len do
mycommand += s[-1*j]
end
p mycommand
Jose Calderon-Celis
5199906-7970
http://www.tm.com.pe/mensajes/



2011/4/22 Rubist Rohit said:
I attempted below given code, but it is neither displaying result nor
error:

================CODE==========================
s = "This is to test reverse of a string"
len = s.length
for j in len..1 do
mycommand = "s.scan(/.$/) {|x| puts x}"
mycommand = mycommand.insert 7,"."
end
==============================================

What I am doing is to insert a period (.) in the seventh or eighth
position on each loop.


spiralofhope wrote in post #994433:
I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above
line in loop?

Here's something I stumbled through which seems to work.

- Using a regex of /.$/
- Slowly chomping away at the original string.
- Using another variable to build my result.

mystring = 'Hello, World!'
result = ''

fail = 0
until fail == "100" or mystring == '' do
fail += 1
mystring.match( %r{(.$)} )
break if $~ == nil
result += $~[1]
mystring = mystring.chomp( $~[1] )
end

puts result
 
S

Stu

Simple =)

s = "1234567890"
r=String.new
i = 1; while i <= s.length
r << s[-i]
i+=1
end

r == s.reverse
true

r is now the reverse of s
 
S

Stu

for j in 1..len do
=A0mycommand +=3D s[-1*j]

very nice I like the use of your math. By multiplying the array index
by negative one your sending the index a reverse number while your for
loop traverses forward. This is perfect logic.

Here is a rewrite with my while loop:

s =3D "1234567890"
r=3DString.new
i =3D 1
while i <=3D s.length
r << s[i*(-1)]
i+=3D1
end
printf s
"0987654321"
=3D> "0987654321"
y =3D=3D x.reverse
true
 
S

Stu

One more with ruby blocks (This would be the ruby way =3D) )

s =3D "1234567890"
r =3D String.new
s.length.times{|i| r << s[(i+1)*(-1)]}

r =3D=3D s.reverse
true

cheers!!!

That was fun!!!... give me another =3D)

~Stu
for j in 1..len do
=A0mycommand +=3D s[-1*j]

very nice I like the use of your math. By multiplying the array index
by negative one your sending the index a reverse number while your for
loop traverses forward. This is perfect logic.

Here is a rewrite with my while loop:

s =3D "1234567890"
r=3DString.new
i =3D 1
while i <=3D s.length
=A0r << s[i*(-1)]
=A0i+=3D1
end
printf s
"0987654321"
=A0=3D> "0987654321"
y =3D=3D x.reverse
true
 
L

Larry Lv

[Note: parts of this message were removed to make it a legal post.]

#!/usr/bin/env ruby

while line = gets.chomp
r = String.new
(1..line.length).each do |i|
r << line[-1*i]
end
puts r
puts r == line.reverse
end

One more with ruby blocks (This would be the ruby way =) )

s = "1234567890"
r = String.new
s.length.times{|i| r << s[(i+1)*(-1)]}

r == s.reverse
true

cheers!!!

That was fun!!!... give me another =)

~Stu
for j in 1..len do
mycommand += s[-1*j]

very nice I like the use of your math. By multiplying the array index
by negative one your sending the index a reverse number while your for
loop traverses forward. This is perfect logic.

Here is a rewrite with my while loop:

s = "1234567890"
r=String.new
i = 1
while i <= s.length
r << s[i*(-1)]
i+=1
end
printf s
"0987654321"
=> "0987654321"
y == x.reverse
true
 
R

Robert Dober

What about

y = lambda{ | str | str.empty? ? "" : y[ str[1..-1] ] + str[0] }

Cheers
Robert
 
H

Harry Kakueki

I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above line
in loop?

--


s = "I am a string."

t = ""
s.each_char{|f| t.insert(0,f)}
p t #> ".gnirts a ma I"




Harry
 
R

Rubist Rohit

Thanks all for brilliant examples.

@jose: Thanks so much. That was too close.

Jose Calderon-Celis wrote in post #994451:
#!/usr/bin/env ruby
#
require 'rubygems'

puts "ruby #{RUBY_VERSION}"
s = "This is to test reverse of a string"
p s
len=s.length
mycommand=""
for j in 1..len do
mycommand += s[-1*j]
end
p mycommand
Jose Calderon-Celis
5199906-7970
http://www.tm.com.pe/mensajes/



2011/4/22 Rubist Rohit <[email protected]>
 
S

spiralofhope

s = "I am a string."

t = ""
s.each_char{|f| t.insert(0,f)}
p t #> ".gnirts a ma I"

Oh, of course! This makes a lot of sense to me..

Some other examples using .length were also very easy on my brain. =)
 
R

Rubist Rohit

@Harry,

That was excellent. Very little code and fits to my condition of not
using arrays as well.

Harry Kakueki wrote in post #994483:
 
J

Jose Calderon-Celis

[Note: parts of this message were removed to make it a legal post.]

@Robert: Thanks, Cheers

#!/usr/bin/env ruby
#
require 'rubygems'

y = lambda{ | str |
# puts " #{str}"
str.empty? ? "" : y[ str[1..-1] ] + str[0]
}

s="1234567890"
p s
p y.call(s)

output:./reverseL.rb
"1234567890"
"0987654321"
 
B

Brian Candler

I'm surprised nobody has yet shown using 'inject', as for once it makes
sense here.

a = "foobar"
puts a.each_char.inject("") { |str,chr| chr+str } # raboof
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit <
I am trying this:

mystring = gets
mystring.scan(/..$/) {|x| puts x}

It returns only the last character. Is it possible to add the above line
in loop?
Thought I'd join the fun :)


s = "12345"

# using reverse
s.reverse # => "54321"


# using each_char
s2 = ""
s.each_char { |char| s2 = char << s2 }
s2 # => "54321"


# using scan
s2 = ""
s.scan(/./) { |char| s2 = char << s2 }
s2 # => "54321"


# using unix (this doesn't escape all chars properly, though)
`rev <<<#{s.inspect}`.chomp # => "54321"


# using recursion
rev = lambda do |string|
if string.empty?
""
else
rev.call(string[1..-1]) << string[0,1]
end
end
rev.call s # => "54321"


# exchanging chars
s2 = s.dup
s2.length./(2).times { |i| s2 , s2[-i-1] = s2[-i-1] , s2 }
s2 # => "54321"
 
D

Duke Normandin

On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit <

Thought I'd join the fun :)

[snip the good stuff]

Now that's what I call a _constructive- reply! All good stuff for
Ruby noobs! While some others here are going into my 'killfile', you
are a rising *star*. :))

It's like a long-time friend of mine used to say - may she rest in
peace! - opinions and advice are like assholes! Everybody's got one!
It's the _informed_ opinions and advice that I'm after - and you seem
to have it! All the other bullshit is going into my bit-bucket - not
now! but right now! :D

Much obliged!
 
A

Adam Prescott

# using reverse
# using each_char
# using scan
# using unix (this doesn't escape all chars properly, though)
# using recursion
# exchanging chars

I feel a benchmark coming, of all the suggestions so far. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top