CMSI 386 QUIZ 1 ANSWERS ======================= PROBLEM 1 --------- class Account def initialize(id) @id = id @balance = 0 end attr_reader :id, :balance def balance=(balance) if (balance < 0) puts "overdrafts not allowed" else difference = balance - @balance action = difference < 0 ? "withdrew from" : "deposited to" @balance = balance puts "#{difference.abs} #{action} account #{@id}" end end end PROBLEM 2 --------- /** * This version does not prevent the balance property from being * accessed directly. You will learn how to do this later in class. * Also, the "side effect" here is really lame: it alerts! */ function Account(id) { this.id = id; this.balance = 0; } Account.prototype.setBalance = function (balance) { if (balance < 0) { alert("overdrafts not allowed"); } else { var difference = balance - this.balance; var action = difference < 0 ? "withdrew from" : "deposited to"; this.balance = balance; alert(Math.abs(difference) + " " + action + " account #" + this.id); } return balance; // To make it just like Ruby } PROBLEM 3 --------- After the script is run, b is [10,10,10,10,10,10,10,10,10,10]. Ten distinct function objects are created. In each the body has a return statement that will return the value of i. In JavaScript whenever you refer to a variable in an expression, you look up the value of the variable right then and there. Each of the functions refer to the variable called i. By the time these functions are called the value of i is 10. PROBLEM 4 --------- def some_nonsense_exam_method(p, a) i = -1 a.collect do |x| (i += 1).times {x = p[x]} x end end PROBLEM 5 --------- function someNonsenseExamMethod(f, a) { var result = []; for (var i = 0; i < a.length; i += 1) { var x = a[i]; for (var j = 0; j < i; j += 1) { x = f(x); } result.push(x); } return result; }