Udemy logo

ruby printRuby programming language is a popular and easy to use language.  Since it is similar in syntax to many existing programming languages it is widely used by budding programmers. Ruby IO is an important part of this scripting language. The print function is one among the many functions which come along with the Ruby IO suite of functions.  Today, in this basic level tutorial, we walk you through print function. We assume that you know the basics of any computer programming language. If not you can take this special beginners course on Ruby which does not require prior programming experience.

Introduction to Ruby

Ruby is a scripting language which was designed by Yukihiro Matsumoto. It runs on platforms such as Windows, Mac OS and different Unix flavors. This language is open source and is freely available on the Web. It is also a general purpose and interpreted programming language. The language is similar to Perl and Python and is widely used for server-side scripting. We can embed, Ruby into HTML. This powerful language is used to write common gate interface (CGI) scripts. Ruby is also used to develop both internet and intranet applications. Note that Ruby has syntax similar to that of many commonly used programming languages like C++ and Perl. The language has easy syntax which allows new programmers to learn it very quickly.  Ruby can easily connect to databases such as Oracle, Sybase, MySQL and DB2. It also offers support to several GUI tools like  GTK, OpenGL and Tcl/Tk. Ruby incorporates a large set of built-in function which can be used directly in to the Ruby code. Also, it is very scalable and easy to maintain.

#!/usr/bin/ruby

The above line gives the location of the ruby executable program. It has to be declared at the beginning of every valid Ruby program. It is also known as the Shebang.

Ruby Print

The Ruby print function is used to display output on the screen. The string or integer value to be printed is passed as an argument to this function. The puts function also displays output. However, puts automatically inserts a newline at the end of the line being printed. Note that print does not do the same. So, while using print, you will have to remember to explicitly add a ‘\n’ at the end, if you want to move to a new line. (To learn more about the Ruby puts function, we suggest that you go take this basic course on Ruby.)

#!/usr/bin/ruby
print "Hello World\n"

In this program, we give the location of the ruby executable program. This program prints “Hello World” on the screen. Simple! Now lets look into some more interesting ways to use the print function.

Example 1: Program to Print Using for Loop

 #!/usr/bin/ruby
for x in 1...100
     print x, " Hello\n";
end

In this program, the ellipses (…) indicates the range. This prints hello 99 times on separate lines.

Note that it stops at 99 and does not print 100. You need to remember this point while using Ruby loops. There are two versions of the ellipses operator. The two period version is inclusive. While the three period version is not.

For example

1..5 means  one through 5.
1...5 means 1 up to but not including 5.

 Example 2: Program to Print from an Array

 #!/usr/bin/ruby
prez = ["Carter", "Reagan", "Bush1", "Clinton", "Bush2","Obama"]
 for ss in 0...prez.length
     print ss, ": ", prez[ss], "\n";
end

 

In this program, we declare a character array containing the names of the presidents. We loop through the array and print each president’s name. Remember that array indexing begins from 0. So whenever you want to print an array, you will need to start your for loop from 0.

Example 3: Program to Print Using Iterators and Blocks

 #!/usr/bin/ruby
prez = ["Carter", "Reagan", "Bush1", "Clinton", "Bush2","Obama"]
prez.each {|president| print president,"\n"}

Note that the ‘each method’ has two arguments – an element and a block. The element is enclosed within the pipes and works like a place holder. Whatever is put in the pipes will be used in the block to represent each array element in turn. The block is the code which is executed on each of the array elements and is given the element to process.

To learn more about arrays in Ruby, you can go through this course which covers it in depth.

Example 3: Program to Print Using the While Loop

 #!/usr/bin/ruby
x = 4
while x > 0
     print x,"\n"
     x -= 1
end
puts "======================"
while x < 5
     print x,"\n"
     x += 1
     break if x > 2
end
puts "======================"
x = 5
while x > 0
     print x,"\n"
     x -= 2
     if x == 1
          x += 5
     end
end

In this program, we have used both the print and puts commands. The while loop will execute as long as its condition evaluates to true. When the condition evaluates to false, the while loop will terminate. This is just a simple example to show you how you can use print in different loops.  To see more examples, you can  take this Ruby course which works out many examples, from scratch.

Example 4: Program Using If and  Elsif Condition

Branching is an important part of programming. In the following program, we check which party a president belonged to. If it satisfies any of the “if”or “else  if” conditions, the corresponding code is executed. Else, if all the conditions are false then code corresponding to else construct is executed.

 #!/usr/bin/ruby
demo = ["Carter", "Clinton"]
rep = ["Ford", "Reagan", "Bush1", "Bush2"]
party = ARGV[0]
if party == nil
     print "Argument must be \"dem\" or \"rep\"\n"
elsif party == "demo"
     demo.each { |i| print i, " "}
     print "\n"
elsif party == "rep"
     rep.each { |i| print i, " "}
     print "\n"
else
     print "All presidents since 1976 were either Democrats or Republicans\n"
end

Note that the “each” syntax which is used iterates through an array in the above program. You can learn more about the ‘each’ command with this course on Ruby programming.

Example 5: Program to Print and Concatenate Strings in Ruby

 #!/usr/bin/ruby
myname = "Dumminy jit"
myname_copy = String.new(myname)
print "myname      = ", myname, "\n"
print "myname_copy = ", myname_copy, "\n"
print "\n=========================\n"
myname << "t"
print "myname      = ", myname, "\n"
print "myname_copy = ", myname_copy, "\n"

Note that strings are part of a class already incorporated in the Ruby programming language. The “<<” is a Ruby string overload for concatenation (that’s just a fancy word for joining). So “t” is appended at the end of “Dumminy Jit.” Hence the new value of myname becomes “Dumminy Jitt.”

Example 6: Program to Print a Substring

#!/usr/bin/ruby
newstr = "Dumminy was here"
print newstr, "\n"
substring = "was"
x = newstr.index(substring)
newstr[x, substring.length] = "is"
print newstr, "\n"

The index string method returns a subscript of the first occurrence of a substring. The starting point for replacement is the return from the index method and the count to replace is the return from the length method. In the above program, the “was” substring is replaced by the string “is.” The output will be “Dumminy is here.”

Ruby Input/Output forms a very important feature of this  major programming language. To summarise, the print function is the part which enables you to display messages, queries or any other text on screen, to interact with the user. The more you use this function, the more you will understand it and use it to the fullest. Go through the examples and then write your own server-side scripting programs to become proficient in Ruby. To learn more advanced Ruby programming, you can check out this course where we walk you through 10 steps to master Ruby programming.

Page Last Updated: April 2014

Featured course

Learn to Code with Ruby

Last Updated September 2023

Bestseller
  • 43 total hours
  • 363 lectures
  • Beginner Level
4.8 (5,651)

A comprehensive introduction to coding with the Ruby programming language. Complete beginners welcome! | By Boris Paskhaver

Explore Course

Ruby students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo