Ruby Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a short practical on how to get started with Ruby:

  1. Create a new directory for your Ruby project and navigate to it in your terminal or command prompt.
  2. Create a new file named greeting.rb and open it in your text editor or IDE.
  3. In the greeting.rb file, write a simple Ruby program that greets a person by their name:
pythonCopy codeprint "What's your name? "
name = gets.chomp
puts "Hello, #{name}!"
  1. Save the file and run it from the terminal or command prompt by typing ruby greeting.rb. You should see a prompt asking for your name, and after entering it, the program should print a greeting using your name.
  2. Next, let’s write a simple program that calculates the factorial of a number. Create a new file named factorial.rb and add the following code:
rubyCopy codedef factorial(n)
  if n <= 1
    1
  else
    n * factorial(n-1)
  end
end

print "Enter a number: "
number = gets.chomp.to_i
puts "The factorial of #{number} is #{factorial(number)}."
  1. Save the file and run it by typing ruby factorial.rb in the terminal or command prompt. You should see a prompt asking for a number, and after entering it, the program should print the factorial of that number.

In this practical, you’ve learned how to write simple Ruby programs that accept input from the user, perform calculations, and print output. This is just a taste of what you can do with Ruby, and you can now start exploring more advanced concepts and techniques to build more complex and sophisticated programs.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *