Chapter 3 is about selections!
We start with boolean data types and of course outline the comparison operators..after a quick glance it appears that all of the comparison operators in Ruby are the exact same as they are in Java.
A variable that holds a Boolean value is known as a Boolean variable. Java uses the reserved word boolean to denote a boolean variable. A boolean variable returns either true or false.
In Ruby there is no boolean variable, true and false belong to seperate classes, which means there is no boolean "type" for now this doesnt really get us off track, but i think is important to note.
In my textbook they throw a math quiz type program at you that is a good example of a way to use a boolean operator.
Here is the code:
import java.util.scanner;
public class MathQuiz{
public static void main (String args [ ]){
int number1 = (int)(System.currentTimeMillis( )% 1o);
int number2 = (int)(System.currentTimeMillis( ) *7 % 10);
// above is just a way to generate a random number
Scanner input = new Scanner (System.in);
// creates a scanner object called "input"
System.out.println("what is " + number1 + "+" + number2 + "?");
// outputs the addition question
int answer = input.nextInt( );
// gets the answer from the input
System.out.println( number1 + "+" + number2 + "=" + answer + "is" + (number1 + number2 ==answer));
// uses a boolean operator to see if answer is correct, if it is it returns true, if not false
}
}
I really like this example in my book, i think it is a very clear way to show how a boolean operator returns a value and its very clever.
Now lets see if I can do it in Ruby
First I will have to find a way to get ruby to list a random integer! go go gadget google search.
Turns out there is a method for that.
Here is a link to a site called stackoverflow where they explain it better than i could.
Great and informative site.
Here is the code in ruby:
class MathQuiz
number1 = rand(10-1) #generates the random number 1
number1 = number1.to_i #converts it to an integer
number2 = rand(10-1) #same as above
number2= number2.to_i
puts ( "what is #{number1} + #{number2} ?") #asks the question
answer1 = gets #gets the input (the guess)
answer1 = answer1.to_i #converts to an int
answer2 = number1 + number2 #computes the actual answer
puts (answer1==answer2) #boolean comparison returns value of true or false
end
And there you have it, some things that i did in this program that i havent done before are :
1. concatenate a string! In Java you put strings in quotes and use the + sign to run them together, in Ruby you use one set of quotes and #{ } to enclose a variable so you can add a value to the string.
2. Use the random number generator method (explained in link above)
3. a boolean comparison (thanks george!) it returns a value of either true or false just like in the good ol java
Thats all for today! Isnt learning fun?
No comments:
Post a Comment