Jump to content

Tranlating into Ruby

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
atrip25

atrip25

    Newbie

  • Members
  • PipPip
  • 26 posts
Ok, I've never worked with Ruby before and I've been given the task of translating a perl program I have into Ruby. Any help would be appreciated.

#!/usr/bin/perl


print "How many lines do you wish to print out? ";


$input = <STDIN>;

$a =a;

$b =b;


while ($count < $input)

{

if ($count < $input)

 {

 push (@array,$a);

 $count = $count + 1;

 print "@array\n";

 }

  if ($count < $input)

  {

  push (@array,$a);

  $count = $count + 1;

  print "@array\n";

  }

   if ($count < $input)

   {

   push (@array,$a);

   $count = $count + 1;

   print "@array\n";

   }

    if ($count < $input)

    {

    push (@array,$b);

    $count = $count + 1;

    print "@array\n";

    }

}



#2
wixifo

wixifo

    Newbie

  • Members
  • PipPip
  • 13 posts
I know it's a pretty old post but I felt like doing it just for the fun of it. And maybe it can help if someone is trying to learn some ruby from perl.


array = Array.new()


print "How many lines do you wish to print out? ";

input = gets.to_i()

a = 'a';

b = 'b';

count = 0

while count < input

	if count < input

		array << a;

		count += 1

		print "#{array} \n"

	end

	if count < input

		array << a;

		count += 1

		print "#{array} \n"

	end 

	if count < input

		array << a;

		count += 1

		print "#{array} \n"

	end 

	if count < input

		array << b;

		count += 1

		print "#{array} \n"

	end 

end


I'm not even sure what's the purpose of this code.

#3
>Ryan

>Ryan

    Newbie

  • Members
  • Pip
  • 2 posts
I saw this thread and just had to sign up and offer my own solution.
def fixup(ary, inp)

  if (ary.size >= inp) then

    ary = ary[0..(inp-1)]

  end

  return ary

end


array = []

puts "How many lines do you wish to print out?"

input = gets.to_i

a = 'a'

b = 'b'

((input.to_f/4).ceil+1).times { |i|

  3.times { |k|

    if (k*i < input):

      array.push a

      puts "#{array}" if array.length < input

    end

    array = fixup(array, input)

  }

  if (i*4 < input):

    array.push b

    puts "#{array}" if array.length < input

  end

  array = fixup(array, input)

}

puts "#{array}"

Certainly not the best/most efficient way of doing it, I know. I wanted to better demonstrate the fact that everything in Ruby is an object.