Every software developer working on a JVM-based stack needs to know how to program in Java, but knowing a peripheral language andlearning Ruby or JavaScript is an invaluable compliment to a developer's skill set.
In a previous tutorial, we implemented a very basic rock-paper-scissors application -- orroshambo as the game is also known -- in Java. Here we will code the same functionality, but we'll use the popular programming language Ruby. Coding the same application in two different languages will demonstrate clearly many of the key differences between Ruby and Java, making it a highly instructive exercise for anyone interested in enhancing their capabilities with either language.
Knowing a peripheral language like Ruby or JavaScript is an invaluable compliment to a Java developer's skill set.
The business requirements for the roshambo application are quite straightforward. The user inputs either rock, paper or scissors as plain text, and the computer displays one of four results: win, lose, tie or error, if the input is bad. To keep the conditional logic fairly simple, the server always chooses rock.
The structure of a Ruby application is much more relaxed and notably more flexible when compared to the Java programming language. Unlike Java, a Ruby application does not require a class definition or the declaration of a method. A Ruby app can be as simple as a text file with nothing but consecutive lines of executable code. When the file is run, Ruby simply runs commands starting at the top of the file and concluding at the bottom.
Variable declarations are always a good way to start a program and our Ruby program requires three: outcome, server_gesture and client_gesture:
outcome = "error"
server_gesture = "rock"
client_gesture = " "
With the variables declared, it's time to take input from the user. A simple call to the methodgets is enough to obtain console input, and adding the method callchomp aftergets will trim any whitespace off the input passed in from the client. Aprint method call preceding thegets.chomp will let the user know that input is expected. Notice that theescape sequence\n is added at the start and end of the prompt. This simply forces a carriage return, helping to format the output:
print "\n Will it be rock, paper or scissors? \n\n"
client_gesture = gets.chomp
With input obtained from the user, the next step is to perform conditional logic to determine the outcome:
if client_gesture == "rock"
outcome = "tie"
end
if client_gesture == "paper"
outcome = "win"
end
if client_gesture == "scissors"
outcome = "loss"
end
With the outcome determined, the last step is to display some output to the user.
In the Java example, we dipped intothe Swing UI toolkit in order to pop up a message box. The reason for that was twofold. First, using GUI components is cool. But more importantly, doing console input with Java is a pain. It's certainly much more difficult than callinggets.chomp, as you would in Ruby. Using Swing components simply represented the path of least resistance. With this Ruby example, the input and output is all console-based. It's a bit boring, but there are opportunities to spice things up a bit.
Ruby has some great text formatting features built into it, so manipulating text is relatively easy. The lines of code that will output the results look like this:
print "\nYou chose #{client_gesture}. "
print "\nThe server chose #{server_gesture}. "
print "\nThe outcome is a #{outcome}.\n"
As you can see, the print lines use an expression language that allows for the direct injection of variable values into the output. Within the text Strings, the entry#{client_gesture} will inject the value of theclient_gesture variable into the output. The same goes for the#{client_gesture} and#{client_gesture} entries. Figure 1 shows what the output looks like when the game runs.
Figure 1. Running the Ruby application at the command line.
As an aid in learning Ruby, here is the full code of the Ruby version of the roshambo game:
# The Ruby version of rock-paper-scissors
# Saved in a file named Roshambo.rb
# Variable declarations
outcome = "error"
server_gesture = "rock"
client_gesture = ""
# Prompt the user and obtain input
print "\nWill it be rock, paper or scissors?\n\n"
client_gesture = gets.chomp
# Perform conditional logic
if client_gesture == "rock"
outcome = "tie"
end
if client_gesture == "paper"
outcome = "win"
end
if client_gesture == "scissors"
outcome = "loss"
end
# Render output to the console
print "\nYou chose #{client_gesture}. "
print "\nThe server chose #{server_gesture}. "
print "\nThe outcome is a #{outcome}.\n"
# End of the roshambo application
To run the application, the text file is saved as Roshambo.rb in the bin directory of the Ruby installation, or anywhere on the file system where the ruby.exe interpreter can be referenced. Then, from the command line, simply run the command>ruby Roshambo.rb:
C:\_ruby22\bin>ruby Roshambo.rb
Figure 2 shows a single run of the game.
Figure 2. A successful run of the roshambo app, written in Ruby.
As you can see, Ruby contrasts with Java in many different ways. Ruby has fewer rules about how the code needs to be organized, the syntax is less verbose, and simple tasks such as formatting code, declaring variables, and obtaining input from the user are greatly simplified. It's no wonder why so many software developers who switch from Java to Ruby are reluctant to ever make the move back.
To reinforce the process of learning Ruby, replace the existing conditional logic in the roshambo application and instead use some of the additional language constructs that Ruby makes available for conditional processing, including else, elsif, unless, when and case statements.
Has your organization switched from Java to Ruby?If so, let us know why.
For those interested in learning Java, or for those who know Java and are interested in leveraging those skills in order to learn a complimentary language like JavaScript or Ruby, TheServerSide is providing a number of problem-driven tutorials that will help you master the fundamentals of these languages.
The catalog of tutorials currently includes the following:
An ADR is only as good as the record quality. Follow these best practices to establish a dependable ADR creation and maintenance ...
At some point, all developers must decide whether to refactor code or rewrite it. Base this choice on factors such as ...
API proxies and gateways help APIs talk to applications, but it can be tricky to understand vendor language around different ...
A principal engineer says Postman's Spec Hub will help the company shift to a spec-first API development process for its ...
AWS Kiro, a project developed by a 'small, opinionated team within AWS,' prioritizes spec-driven development in the workflows of ...
Docker is expanding the Docker Compose spec to accommodate AI agents in an effort to bring AI development closer to existing ...
AI is transforming PaaS with automation and cost-efficient features, but will it eventually replace cloud platforms? Industry ...
Even though Q-Day might be several years away, enterprises should develop a strategic plan to prepare for the future. Experts ...
Businesses can find security vulnerabilities when they push their workloads to the edge. Discover the pitfalls of cloud edge ...
Runtime security and tokenization stand to play a bigger role in attack surface management, a development that could influence ...
Check out the latest security news from the Informa TechTarget team.
How CISOs design and build their security teams is as important as the technology they select to safeguard their organizations' ...
Compare Datadog vs. New Relic capabilities including alerts, log management, incident management and more. Learn which tool is ...
Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates ...
There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service ...