quiz1-soln-fall11

Quiz1-soln-fall11 - a.each |x| puts x if x 3(14 pts Given an array of strings x write a Ruby method printWords x using Hash and code blocks to go

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
CMSC330 Fall 2011 Quiz #1 Solutions 1. (4 pts) Explain why languages like Java do not use implicit declarations. Because errors (such as misspelled identifiers) will not be caught at compile time. 2. (12 pts) What is the output (if any) of the following Ruby programs? Write FAIL if code does not execute. a. (4 pts) a = [ ] # Output = Fail a[“foo”] = 5 puts a[5] b. (4 pts) a = { } # Output = Found 4 a[“bar”] = 4 puts “Found #{ a[“bar”] }” c. (4 pts) a = [ ] # Output = Terp a[3] = “Terp”
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: a.each { |x| puts x if x } 3. (14 pts) Given an array of strings x , write a Ruby method printWords( x ) using Hash and code blocks to go through the array elements in order, printing out all strings in x the first time they are encountered, with each string on a separate line. In other words, print out all strings in x if the string has not been printed already. Answer: def printWords( x ) counts = { } x.each { |a| if counts[a] == nil puts a counts[a] = 1 end } end...
View Full Document

This note was uploaded on 01/13/2012 for the course CMSC 330 taught by Professor Staff during the Fall '08 term at Maryland.

Ask a homework question - tutors are online