
CMSC 330, Practice Problems 1 (SOLUTIONS)
1. Programming languages
a. Explain how goals for programming languages have changed since the 1960โs.
Shifted from efficiency to ease-of-programming
b. List 2 desirable attributes for a programming language where Ruby is better
than C. Explain why.
Naturalness of application โ Text processing is easier in Ruby
Cost of use โ Small Ruby programs are simpler/quicker to write
c. List 2 methods for executing a program. Which method is used by Ruby?
Interpretation & compilation. Ruby is interpreted.
d. Explain why Ruby fits the definition of a scripting language.
Rich text processing (Regexp) and easy to use (implicit declarations)
2. Ruby basics
a. Write a Ruby method foo that takes an integer as a parameter. Call foo with 2
as its argument. Circle & label the formal and actual parameters in your code.
def foo(x) โฆ end ; foo(2) ; // x = formal param, 2 = actual parameter
b. Using different Ruby control statements, write 4 code fragments that iterate
from i=1 to i=10.
1.upto(10) {|i| puts i; }
(1..10).each {|i| puts i; }
for i in (1..10) do puts i; end
i=1; while i<=10 do puts i; i+=1; end
i=1; do puts i; break if (i+=1)>10 end
c. Explain the difference between explicit and implicit variable declarations.
Explicit โ declaration statements declare type of each variable used
Implicit โ first use of a variable declares it and determines its type
d. List two advantages of static types.
Helps prevent subtle errors, catches more type errors at compile time
e. Using Ruby, write a class Teacher that contains an integer field students and
an integer field totalStudents that is shared across all objects of class Teacher.
class Teacher
@@totalStudents = 0
def initialize
@students = 0
@@totalStudents += @students
end
end
f. Give an example of reference copy in Ruby.
x = โaโ ; y = x
g. Give an example of testing for structural equality in Ruby.
x == y