3.9 Exercises

  1. You saw that Ruby does not allow addition of floats and strings. For example:

    irb(main):005:0> 1.1 + "string"
    TypeError: String can't be coerced into Float
         from /Users/leland/.irbrc:73(irb):1:in '+'
         from (irb):14

    What type combinations does Ruby allow to be added?

  2. Using irb, initialize three variables, x, y, and z, each to some number less than 10. Design an equation with these variables using at least one multiplication, one division, and one addition or subtraction element. Have the computer do it once without parentheses, and then add parentheses to the equation and try it again. Are the answers the same? If not, why not?

  3. Earlier in the chapter, we saw the following:

    irb(main):001:0> 1.0 * 5 / 2
    => 2.5

    Now, try typing the following code into irb:

    irb(main):002:0> 5 / 2*1.0

    This should have produced a value of 2.0. Why does it produce the value 2.0, and not 2.5, like we saw earlier?

  4. Write the expected value of x after both lines are executed.

    1. irb(main):001:0> x = 9
      irb(main):002:0> x = x/2
    2. irb(main):003:0> x = 9
      irb(main):004:0> x = x/2.0
  5. What is the expected result of c for each code group?

    1. irb(main):001:0> a = Math.sqrt(9)
      irb(main):002:0> b = 2
      irb(main):003:0> c = a/b
    2. irb(main):001:0> a = 5
      irb(main):002:0> b = 2
      irb(main):003:0> c = a/b
  6. Suppose a program finds the average temperature for a given year. A user of the program is prompted to enter the average temperature values for each season of the year: winter, spring, summer, and fall. The program ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.