Why Is My Terminal Reading My Code as Java When It's Ruby

Chapter 1. More with Less: Code the Way You Want

image with no caption

You're wondering what this crazy Ruby language is all about, and if it's right for you. Let the states enquire y'all this: Do you lot similar being productive? Do you experience like all those actress compilers and libraries and grade files and keystrokes in your other language bring you closer to a finished production , admiring coworkers , and happy customers ? Would yous similar a language that takes care of the details for you? If you sometimes wish you could stop maintaining boilerplate lawmaking and become to piece of work on your problem , and then Ruby is for you lot. Ruby lets you go more washed with less code.

The Ruby-red philosophy

Back in the 1990s in Japan, a programmer named Yukihiro Matsumoto ("Matz" for short) was dreaming about his ideal programming language. He wanted something that:

  • Was easy to learn and use

  • Was flexible enough to handle any programming task

  • Let the programmer concentrate on the problem they were trying to solve

  • Gave the developer less stress

  • Was object-oriented

He looked at the languages that were available, merely felt that none of them was exactly what he wanted. And so he set out to brand his own. He called it Ruby.

After tinkering around with Ruby for his own work for a while, Matz released it to the public in 1995. Since then, the Ruby community has done some amazing things:

  • Congenital out a vast collection of Crimson libraries that can aid you do anything from reading CSV (comma-separated value) files to controlling objects over a network

  • Written alternate interpreters that tin run your Ruby lawmaking faster or integrate it with other languages

  • Created Ruby on Rails, a hugely pop framework for web applications

This explosion of creativity and productivity was enabled past the Scarlet language itself. Flexibility and ease of use are cadre principles of the language, meaning yous can use Reddish to achieve any programming chore, in fewer lines of code than other languages.

In one case y'all've got the basics down, you lot'll concord: Ruby is a joy to use!

Flexibility and ease of use are core principles of Blood-red.

Get Red

First things commencement: you can write Ruby lawmaking all twenty-four hours, merely it won't do you much good if you can't run it. Let's make sure you have a working Scarlet interpreter installed. Nosotros want version 2.0 or later. Open up upwards a new concluding window (also known as a command-line prompt ) and type:

reddish -v

image with no caption

When you type cherry-red -v at a prompt, if you see a response like this, yous're in business:

image with no caption

Do this!

If you don't take Ruby-red 2.0 or later, visit world wide web.cerise-lang.org and download a copy for your favorite Bone.

By the fashion, if you lot accidentally type ruby by itself (without the -v), Ruby volition expect for you lot to enter some code. To exit this mode, just hold the Command cardinal and press the C key on your keyboard. You can do this any fourth dimension you lot need Ruby to exit immediately.

Apply Crimson

Ruby source files that you can execute are referred to as scripts , simply they're really but obviously-text files. To run a Ruby script, you simply save your Ruby code in a file, and run that file with the Ruby interpreter.

Y'all may exist used to other languages (similar C++, C#, or Java) where y'all have to manually compile your code to a binary format that a CPU or virtual machine can sympathize. In these languages, your lawmaking tin can't be executed earlier you compile it.

Other languages:

image with no caption

With Ruby, y'all skip that step . Ruby instantly and automatically compiles the source code in your script. This means less fourth dimension between writing your code and trying it out!

The Ruddy fashion:

image with no caption

image with no caption

Type your source code. Save every bit: howdy.rb

image with no caption

Run your source code with the Ruby interpreter.

Employ Cherry-red—interactively

In that location's another big benefit to using a language like Ruby. Not only do you lot not have to run a compiler each time yous want to try out your code, but you lot don't even have to put it in a script first.

Scarlet comes with a separate program, called irb (for I nteractive R u b y). The irb vanquish lets you type whatever Ruby expression, which it will then immediately evaluate and evidence you the results. It'south a great fashion to learn the linguistic communication, considering yous get immediate feedback. But fifty-fifty Ruddy professionals use irb to try out new ideas.

Throughout the book, nosotros'll be writing lots of scripts to be run via the Ruby interpreter. But whatsoever time yous're testing out a new concept, it'due south a corking idea to launch irb and experiment a bit.

And so what are we waiting for? Let's get into irb now and play around with some Cherry-red expressions.

Using the irb shell

Open a terminal window, and type irb . This will launch the interactive Ruby interpreter. (You'll know it'southward running because the prompt will change, although it may non match exactly what you come across here.)

From in that location, you tin can type whatever expression you desire, followed past the Enter/Return cardinal. Red volition instantly evaluate it and show y'all the result.

When you're done with irb, type exit at the prompt, and y'all'll exist returned to your Os'due south prompt.

image with no caption

Your first Ruby expressions

Now that you know how to launch irb, permit's try out a few expressions and see what results nosotros get!

Type the following at the prompt, then printing Return: i + 2

Yous'll be shown the consequence:

image with no caption

Math operations and comparisons

Ruby'south basic math operators work just like they do in most other languages. The + symbol is for improver, - for subtraction, * for multiplication, / for sectionalization, and ** for exponentiation.

image with no caption

You can employ < and > to compare ii values and see if one is less than or greater than another. Yous can also apply == (that'due south two equals signs) to see if two values are equal.

image with no caption

Strings

A string is a series of text characters. You lot tin can apply strings to concord names, email addresses, telephone numbers, and a million other things. Ruby's strings are special because fifty-fifty very large strings are highly efficient to work with (this isn't truthful in many other languages).

The easiest fashion to specify a string is to surround it either with double quotes (") or single quotes ('). The two types of quotes work a little differently; we'll encompass that later in the chapter.

image with no caption

Variables

Red lets us create variables —names that refer to values.

You don't have to declare variables in Ruby; assigning to them creates them. Y'all assign to a variable with the = symbol (that'due south a single equals sign).

image with no caption

A variable name starts with a lowercase letter, and tin contain letters, numbers, and underscores.

One time yous've assigned to variables, y'all can access their values whenever you lot need, in any context where you might apply the original value.

image with no caption

Variables don't have types in Carmine; they can hold any value you want. You can assign a string to a variable, then immediately assign a floating-bespeak number to the same variable, and it's perfectly legal.

image with no caption

The += operator lets you add on to the existing value of a variable.

image with no caption

Conventional Wisdom

Use all lowercase letters in variable names. Avoid numbers; they're rarely used. Split words with underscores.

my_rank = 1

This style is sometimes called "snake case," considering the underscores make the proper noun expect like it's itch on the ground.

Everything is an object!

Ruby is an object-oriented language. That ways your data has useful methods (fragments of lawmaking that you tin execute on demand) fastened directly to it.

In modern languages, information technology's pretty common for something like a cord to be a full-fledged object, so of course strings have methods to telephone call:

image with no caption

What's absurd nearly Blood-red, though, is that everything is an object. Even something equally simple as a number is an object. That ways numbers have useful methods, too.

image with no caption

Calling a method on an object

When you make a call like this, the object you lot're calling the method on is known as the method receiver . Information technology'south whatever is to the left of the dot operator. You lot can think of calling a method on an object as passing information technology a message —like a note proverb, "Hey, can you send me back an capital version of yourself ?" or "Can I take your absolute value?"

image with no caption

Allow'southward build a game

In this first chapter, we're going to build a simple game. If that sounds daunting, don't worry; it's easy when you're using Ruby!

Let's look at what we'll need to exercise:

Input, storage, and output

Our first requirement is to greet the user past name. To accomplish that, we'll need to write a script that gets input from the user, stores that input, then uses that stored value to create some output .

We tin can do all this in but a few lines of Ruddy code:

image with no caption

We'll go into detail on each component of this script over the next few pages. But first, let's give it a attempt!

Running scripts

We've written a simple script that fulfills our first requirement: to greet the player by proper name. Now, you'll larn how to execute the script then y'all can see what you've created.

Do this!

Pace I:

Open a new document in your favorite text editor, and blazon in the post-obit code.

image with no caption

Step Ii:

Relieve the file as get_number.rb .

Stride 3:

Open up a final window and change into the directory where you saved your program.

Step Four:

Run the program past typing cherry-red get_number.rb .

image with no caption

Step 5:

You'll come across a greeting and a prompt. Type your name and hit the Enter/Render key. Y'all'll then encounter a message that welcomes you by proper name.

Let'southward take a few pages to await at each function of this code in more detail.

Our source file starts out with a couple of comments. Scarlet ignores everything from a hash mark (#) up until the terminate of the line, so that you tin can leave instructions or notes for yourself and your fellow developers.

image with no caption

If you place a # in your code, then everything from that point until the end of the line will be treated as a comment. This works just like the double-slash (//) marker in Java or JavaScript.

i_am = "executed" # I'm not. # Me neither.

"puts" and "print"

The actual code starts with a call to the puts method ("puts" is short for " put s tring"), which displays text on standard output (usually the terminal). We pass puts a cord containing the text to display.

image with no caption

We pass another cord to the impress method on the following line, to ask the user their name. The print method works just like puts, except that puts adds a newline graphic symbol at the end of the cord (if it doesn't already accept ane) to skip to the following line, whereas print doesn't. For cosmetic reasons, nosotros end the string that we pass to impress with a space, so that our text doesn't run upwards against the surface area where the user types their proper noun.

image with no caption

Sometimes you don't have to specify a receiver for method calls.

The puts and print methods are so important, and and so unremarkably used, that they're amongst a select few methods that take been included in Cherry'south peak-level execution environment . Methods defined in the peak-level environment are available for y'all to call anywhere in your Ruby lawmaking, without specifying a receiver. You'll run into how to define methods like this at the first of Chapter 2.

Method arguments

The puts method takes a cord and prints it to standard output (your terminal window).

puts "first line"

image with no caption

The cord passed to the puts method is known as the method argument .

The puts method can take more than than one statement; just separate the arguments with commas. Each argument gets printed on its own line.

puts "2d line", "third line", "fourth line"

"gets"

The gets method (brusque for " get s tring") reads a line from standard input (characters typed in the terminal window). When y'all call gets, it causes the program to halt until the user types their name and presses the Enter key. It returns the user's text to the program as another cord.

image with no caption

As with puts and impress, yous can call the gets method from anywhere in your lawmaking without specifying a receiver.

Parentheses are optional on method calls

Method arguments tin be surrounded with parentheses in Carmine:

puts("one", "two")

Just the parentheses are optional, and in the case of puts, most Rubyists prefer to leave them off.

puts "ane", "ii"

Equally noted above, the gets method reads a line from standard input. It doesn't (usually) need any arguments:

gets

Rubyists are adamant that parentheses not exist used if a method takes no arguments. So please, don't do this, even though it's valid code:

image with no caption

Conventional Wisdom

Go out parentheses off of a method call if at that place are no arguments. You can leave them off for method calls where at that place are arguments as well, merely this can brand some code more than difficult to read. When in doubt, apply parentheses!

String interpolation

The last thing our script does is to call puts with i more than string. This one is special because nosotros interpolate (substitute) the value in the name variable into the string. Whenever you include the #{...} notation inside a double-quoted string, Ruby uses the value in the curly braces to "fill in the blank." The #{...} markers can occur anywhere in the string: the outset, end, or somewhere in the heart.

image with no caption

You're non limited to using variables within the #{...} marker—you can use any Red expression.

image with no caption

Note that Blood-red applies interpolation only in double- quoted strings. If yous include a #{...} marker in a single -quoted cord, it will be taken literally.

image with no caption

Reddish doesn't require a bunch of ceremony for elementary programs.

What's in that string?

image with no caption

image with no caption

Well, that'south like shooting fish in a barrel plenty to add. Let's throw an exclamation point on the finish of the greeting cord, afterward the interpolated value.

image with no caption

Merely if we endeavour running the program again, we'll see that rather than actualization immediately after the user's proper name, the assertion point jumps down to the next line!

image with no caption

Why is this happening? Maybe in that location'southward something going on within that input variable...

Printing it via the puts method doesn't reveal annihilation special about it, though. If we suspend this line to the code above, we'd see this output:

image with no caption

Inspecting objects with the "inspect" and "p" methods

At present allow'southward try again, using a method meant especially for troubleshooting Crimson programs. The inspect method is available on any Reddish object. It converts the object to a string representation that's suitable for debugging. That is, it will reveal aspects of the object that don't normally show up in program output.

Hither's the result of calling inspect on our string:

image with no caption

What'south that \north at the end of the cord? We'll solve that mystery on the next page...

Printing the result of inspect is so common that Ruby offers some other shortcut: the p method. It works only like puts, except that information technology calls inspect on each statement before press information technology.

This telephone call to p is effectively identical to the previous code:

image with no caption

Call back the p method; nosotros'll be using it in after chapters to help debug Ruby code!

The "inspect" method reveals information nearly an object that doesn't usually show upwardly in programme output.

Escape sequences in strings

Our use of the p method has revealed some unexpected data at the end of the user'south input:

image with no caption

These ii characters, the backslash (\) and the due north that follows information technology, actually represent a unmarried character: a newline character. (The newline graphic symbol is named thus because it makes concluding output jump downward to a new line .) In that location's a newline at the cease of the user input because when the user hits the Return key to signal their entry is washed, that gets recorded every bit an actress character. That newline is then included in the return value of the gets method.

Ordinarily used escape sequences

If you include this in a double-quoted cord...

...yous get this character...

\n

newline

\t

tab

\"

double-quotes

\'

single-quote

\\

backslash

The backslash character (\) and the n that follows it are an escape sequence —a portion of a cord that represents characters that can't unremarkably be represented in source code.

The nigh commonly used escape sequences are \n (newline, as we've seen) and \t (a tab graphic symbol, for indentation).

image with no caption

Normally, when y'all attempt to include a double-quotation mark (") in a double-quoted string, it gets treated as the end of the string, leading to errors:

image with no caption

If you lot escape the double-quotation marks past placing a backslash before each, you can place them in the middle of a double-quoted string without causing an error.

image with no caption

Lastly, because \ marks the offset of an escape sequence, nosotros besides need a way to represent a backfire character that isn't part of an escape sequence. Using \\ will give us a literal backslash.

image with no caption

Bear in listen that almost of these escape sequences use only in double -quoted strings. In single- quoted strings, well-nigh escape sequences are treated literally.

image with no caption

Calling "chomp" on the string object

image with no caption

image with no caption

We tin can employ the chomp method to remove the newline character.

If the last character of a string is a newline, the chomp method will remove information technology. It's great for things like cleaning upward strings returned from gets.

The chomp method is more specialized than print, puts, and gets, then information technology'southward bachelor only on individual string objects. That means we need to specify that the string referenced by the input variable is the receiver of the chomp method. We need to use the dot operator on input.

image with no caption

The chomp method returns the same cord, but without the newline graphic symbol at the end. We store this in a new variable, name, which we and so print as role of our welcome message.

If we try running the program again, we'll come across that our new, emphatic greeting is working properly now!

image with no caption

What methods are bachelor on an object?

Yous tin't call just any method on just any object. If you effort something like this, y'all'll get an error:

image with no caption

Which, if you lot think nearly it, isn't and then wrong. After all, it doesn't make a lot of sense to capitalize a number, does it?

But, and so, what methods can you call on a number? That question can be answered with a method called methods:

image with no caption

If you call methods on a string, yous'll get a dissimilar list: puts "hello".methods

image with no caption

Why the difference? It has to do with the object's course. A class is a blueprint for making new objects, and it decides, among other things, what methods y'all tin can call on the object.

There's some other method that lets objects tell us what their class is. Information technology's called, sensibly plenty, class. Permit's endeavour information technology out on a few objects.

image with no caption

We'll be talking more than nigh classes in the next chapter, so stay tuned!

That's all the lawmaking for our kickoff requirement. You can bank check it off the list!

Generating a random number

Our histrion greeting is done. Let's await at our next requirement.

The rand method will generate a random number within a given range. It should exist able to create a target number for u.s.a..

We demand to laissez passer an argument to rand with the number that volition be at the upper terminate of our range (100). Let's try it out a couple of times:

image with no caption

Looks good, but there'southward one problem: rand generates numbers between zero and only beneath the maximum value y'all specify. That means we'll exist getting random numbers in the range 0–99, non 1–100 like we need.

That's easy to fix, though. We'll just add 1 to whatever value we go back from rand. That will put us back in the range of ane–100!

rand(100) + 1

We'll store the consequence in a new variable, named target.

image with no caption

Converting to strings

That's some other requirement downwardly! Let's look at the next one...

"Keep rails of how many guesses the player has made..." Looks like we'll need a variable for the number of guesses. Obviously, when the role player showtime starts, they haven't made whatsoever guesses, then we'll create a variable named num_guesses that's set to 0 initially.

num_guesses = 0

Now, the first thing you might attempt to do in order to display the number of guesses remaining is to concatenate (join) the strings together using the plus sign (+), every bit many other languages exercise. Something similar this won't work , notwithstanding:

image with no caption

The + operator is used to add numbers too as to concatenate strings , and since remaining_guesses contains a number, this plus sign looks like an attempt to add numbers.

What's the solution? You need to catechumen the number to a string. Nearly all Ruby objects have a to_s method you tin call to do this conversion; let's try that now.

image with no caption

That works! Converting the number to a cord first makes information technology clear to Crimson that you're doing concatenation, not addition.

Ruby provides an easier way to handle this, though. Read on...

Ruby makes working with strings like shooting fish in a barrel

Instead of calling to_s, we could salvage ourselves the effort of explicitly converting a number to a string past using string interpolation. Every bit you saw in our code to greet the user, when yous include #{...} in a double-quoted string, code inside the curly braces is evaluated, converted to a string if necessary, and interpolated (substituted) into the longer cord.

The automatic string conversion means nosotros tin can get rid of the to_s telephone call.

image with no caption

Crimson lets u.s. do operations directly inside the curly braces, and so we tin can also get rid of the remaining_guesses variable.

image with no caption

The #{...} can occur anywhere within the cord, so it's easy to make the output a little more user-friendly, too.

image with no caption

Now the histrion volition know how many guesses they take left. Nosotros can check some other requirement off our list!

image with no caption

Converting strings to numbers

Our next requirement is to prompt the histrion to judge the target number. So we need to print a prompt, then record the user'southward input as their approximate. The gets method, as you may recall, retrieves input from the user. (We already used it to get the player'due south name.) Unfortunately, nosotros can't just use gets past itself to get a number from the user, because it returns a string. The problem will arise later, when nosotros try to compare the player's guess with the target number using the > and < operators.

image with no caption

We demand to convert the cord returned from the gets method to a number and so that nosotros tin compare the guess to our target number. No problem! Strings have a to_i method to do the conversion for usa.

Mutual conversions

If yous call this method on an object...

...you get this kind of object back.

to_s

string

to_i

integer

to_f

floating-point number

This code will call to_i on the cord returned from gets. Nosotros don't fifty-fifty need to put the cord in a variable beginning; we'll just utilize the dot operator to call the method directly on the return value.

approximate = gets.to_i

When you call to_i on a string, it ignores any non-numeric characters that follow the number. So nosotros don't even need to remove the newline character left by gets.

If we want to test our changes, we can print out the upshot of a comparison.

image with no caption

Much ameliorate—we have a guess that we can compare to the target. That's another requirement done!

image with no caption

Conditionals

Two more requirements for our game down, iv to get! Permit's look at the next batch.

Now, nosotros need to compare the player'southward guess with the target. If it's too high, nosotros print a bulletin saying then. Otherwise, if it'due south as well low, we print a message to that effect, and so on... Looks like we demand the ability to execute portions of our code only under certain weather condition .

Similar most languages, Carmine has provisional statements: statements that crusade code to be executed only if a condition is met. An expression is evaluated, and if its result is truthful, the code in the conditional body is executed. If not, information technology's skipped.

image with no caption

As with most other languages, Blood-red supports multiple branches in the condition. These statements take the grade if/elsif/else.

image with no caption

Conditionals rely on a Boolean expression (one with a true or false value) to decide whether the code they contain should be executed. Ruby has constants representing the ii Boolean values, true and false.

if truthful   puts "I'll be printed!" end
if imitation   puts "I won't!" end

Ruby as well has all the comparison operators you're used to.

image with no caption

It has the Boolean negation operator, !, which lets y'all have a true value and make it false, or a false value and make it true. It besides has the more-readable keyword not, which does basically the same affair.

if ! true   puts "I won't be printed!" finish  if ! faux   puts "I will!" end
if not true   puts "I won't be printed!" end  if non faux   puts "I will!" finish

If you need to ensure that 2 conditions are both truthful, you can use the && ("and") operator. If you lot need to ensure that either of 2 weather condition is true, you can employ the || ("or") operator.

if true && true   puts "I'll exist printed!" cease  if true && false   puts "I won't!" end
if simulated || true   puts "I'll exist printed!" stop  if false || false   puts "I won't!" end

image with no caption

No, Crimson doesn't treat indentation as significant to the meaning of the program (unlike some other languages, such every bit Python).

Merely indenting lawmaking within if statements, loops, methods, classes, and the like is simply good coding way. It helps brand the structure of your code clear to your beau developers (and fifty-fifty to yourself).

We need to compare the player's guess to the random target number. Let's apply everything we've learned virtually conditionals to implement this batch of requirements.

image with no caption

The contrary of "if" is "unless"

This statement works, but it'due south a little bad-mannered to read:

if not guessed_it   puts "Deplorable. Yous didn't get my number. (It was #{target}.)" end

Conventional Wisdom

Information technology's valid to utilise else and elsif together with unless in Cerise:

image with no caption

Simply it'south very difficult to read. If you demand an else clause, utilise if for the principal clause instead!

image with no caption

In most respects, Ruby's conditional statements are simply like about other languages. Ruby has an additional keyword, though: unless.

Code within an if statement executes only if a status is true , simply code within an unless statement executes just if the condition is false .

unless true   puts "I won't be printed!" finish
unless fake   puts "I will!" end

The unless keyword is an case of how Ruby works hard to make your code a little easier to read. Y'all can use unless in situations where a negation operator would exist awkward. And so instead of this:

if ! (calorie-free == "cherry-red")   puts "Become!" end

Y'all can write this:

unless lite == "scarlet"   puts "Get!" terminate

We can use unless to clean up that final conditional.

unless guessed_it   puts "Sorry. You didn't get my number. (It was #{target}.)" end

Much more legible! And our conditional statements are working great!

image with no caption

Note

You'll see something like this if y'all run get_number.rb at present...

As it stands right now, though, the player gets only i guess—they're supposed to get 10. Nosotros'll ready that side by side...

Loops

Slap-up work so far! Nosotros have just 1 more than requirement to go for our guessing game!

Currently, the player gets one approximate. Since at that place's 100 possible target numbers, those don't seem like very fair odds. Nosotros need to keep asking the thespian 10 times, or until they become the correct answer, whichever comes first.

The code to prompt for a judge is already in place, and so we just need to run it more than than once . We tin can employ a loop to execute a segment of code repeatedly. You've probably encountered loops in other languages. When you lot need one or more than statements to be executed over and over, y'all identify them within a loop.

image with no caption

A while loop consists of the word while, a Boolean expression (just like in if or unless statements), the code you lot desire to repeat, and the word stop. The code within the loop body repeats while the condition is truthful.

Here'due south a unproblematic example that uses a loop for counting.

image with no caption

Just every bit unless is the counterpart to if, Ruby offers an until loop equally a counterpart to while. An until loop repeats until the condition is true (that is, it loops while it's fake).

Here's a similar example, using until.

image with no caption

Hither'due south our conditional code again, updated to run within a while loop:

image with no caption

There'southward one more readability improvement we tin can make. As with the if argument that nosotros replaced with an unless, nosotros tin make this while loop read more clearly past replacing it with an until.

Before:

while num_guesses  <  x && guessed_it == false   ... end

After:

until num_guesses == 10 || guessed_it   ... end

Hither's our complete lawmaking listing.

image with no caption

Let's try running our game!

Our loop is in place—that'south the last requirement! Let's open up a terminal window and effort running the program!

image with no caption

image with no caption

Using variables, strings, method calls, conditionals, and loops, yous've written a complete game in Ruby! Better nonetheless, information technology took fewer than 30 lines of code! Pour yourself a cold drinkable—you've earned it!

You've got Chapter one under your belt and at present you've added method calls, conditionals, and loops to your toolbox.

Statements

Conditional statements execute the lawmaking they enclose if a status is met.

Loops execute the code they enclose repeatedly. They exit when a condition is met.

Up Side by side...

All your code is in ane big lump correct now. In the next affiliate, you'll learn how to break your code into easily maintainable chunks, using classes and methods.

bronsongoomects.blogspot.com

Source: https://www.oreilly.com/library/view/head-first-ruby/9781449372644/ch01.html

0 Response to "Why Is My Terminal Reading My Code as Java When It's Ruby"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel