Skip to content

Commit 0d26100

Browse files
committed
Added selected book problem solutions
1 parent 50e4194 commit 0d26100

File tree

1 file changed

+156
-0
lines changed

1 file changed

+156
-0
lines changed

2013-01-22-book-problems-solution.md

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Ruby Self-Study
2+
3+
## Day 1
4+
5+
### Find
6+
7+
* [The Ruby API][Ruby API]
8+
* The free online version of [_Programming Ruby: The Pragmatic Programmer's Guide_][Programming Ruby]
9+
* [A method][gsub] that substitutes part of a string
10+
11+
```ruby
12+
>> foo = 'The quick brown fox jumps over the lazy dog.'
13+
>> foo['The'] = 'A' # Replace first occurrence of "The" in string foo
14+
>> foo.sub('quick', 'fast') # Returns copy of foo with "quick" replaced with "fast"
15+
>> foo.sub!(/quick/, 'speedy') # Replaces substring "quick" with "speedy" in place (we use a regex pattern just for the sake of demonstration)
16+
>> foo.gsub!(/a/i, 'the') # Case-insensitive, replace all occurrences of "a" with "the" in-place
17+
```
18+
19+
* [Ruby's regular expressions][Regex]
20+
* [Ruby's ranges][Range]
21+
22+
### Do
23+
24+
Print the string "Hello, World"
25+
```ruby
26+
puts "Hello, world."
27+
```
28+
29+
For the string “Hello, Ruby,” find the index of the word “Ruby.”
30+
```ruby
31+
'Hello, Ruby' =~ /Ruby/ # Using regular expression matching
32+
'Hello, Ruby'.index('Ruby') # Using the index method
33+
```
34+
35+
Print your name 10 times
36+
```ruby
37+
puts "Kevin Gao\n" * 10
38+
10.times { puts "Yang Su" }
39+
```
40+
41+
Print the string "This is sentence number 1," where the number 1 changes from 1 to 10.
42+
```ruby
43+
(1..10).each do |num| # Using a range
44+
puts "This is sentence number #{num}"
45+
end
46+
47+
1.upto(10) do |num| # Using an enumerator
48+
puts "This is sentence number #{num}"
49+
end
50+
```
51+
52+
Run a Ruby program from a file
53+
```bash
54+
ruby 01-randnumgame.rb
55+
```
56+
57+
Bonus problem: write a program that picks a random number. Let a player guess the number, telling the player whether the guess is too low or too high.
58+
59+
```ruby
60+
def getRandAnswer(max = 10)
61+
rand(max) + 1
62+
end
63+
64+
STDOUT.sync
65+
66+
puts "Welcome to the random number game!"
67+
puts "\tTo quit, answer 'q' at any time"
68+
69+
guess = nil
70+
max = 10
71+
answer = getRandAnswer(10)
72+
73+
while true
74+
puts "Guess a number from 1 to #{max}:"
75+
guess = gets.chomp
76+
break if guess == 'q'
77+
78+
gNum = guess.to_i
79+
if gNum == answer
80+
puts "Correct!"
81+
answer = getRandAnswer(10)
82+
elsif gNum < answer
83+
puts "Too low"
84+
else
85+
puts "Too high"
86+
end
87+
end
88+
```
89+
90+
## Day-2: Self-Study
91+
### Find
92+
93+
* Find out how to access files with and without code blocks. What is the benefit of the code block?
94+
95+
```ruby
96+
# With code blocks
97+
File.open('foo.bar', 'w') { |f| f << 'bazzbuzz' }
98+
99+
# Without code blocks
100+
file = File.open('foo.bar', 'w')
101+
file << 'bazzbuzz'
102+
file.close
103+
```
104+
The benefit of using a code block is that it wraps resource handling policies around the block, rather than the coder using the API having to deal with it. Also, it's just pretty.
105+
106+
* How would you translate a hash to an array? `Hash.values`. Can you translate arrays to hashes? `Hash[*array]`.
107+
108+
* Can you iterate through a hash? _Yes_.
109+
```ruby
110+
{:array=>[1, 2, 3], :string=>"Hello"}.each {|k, v| puts "k: #{k}, v: #{v}"}
111+
# => k: array, v: [1, 2, 3]
112+
# => k: string, v: Hello
113+
```
114+
115+
* You can use Ruby arrays as stacks. What other common data structures do arrays support? _Queues_, _Sets_
116+
117+
### Do
118+
119+
Print the contents of an array of sixteen numbers, four numbers at a time, using just each. Now, do the same with each_slice in Enumerable.
120+
```ruby
121+
a = (1..16).to_a
122+
b = []
123+
a.each do |x|
124+
b.push x
125+
if b.length == 4
126+
puts b.join(',')
127+
b.clear
128+
end
129+
end
130+
131+
a = (1..16).to_a
132+
a.each_slice(4) { |xs| puts xs.join(',') }
133+
```
134+
135+
**The solution to the Tree problem will be released after the assignment is due**
136+
137+
Write a simple grep that will print the lines of a file having any occurrences of a phrase anywhere in that line. You will need to do a simple regular expression match and read lines from a file. (This is surprisingly simple in Ruby.) If you want, include line numbers.
138+
```ruby
139+
def grep(filename, phrase)
140+
File.open(filename, 'r').each_with_index do |line, lineNumber|
141+
puts "#{lineNumber}: #{line}" if line =~ /#{phrase}/
142+
end
143+
end
144+
```
145+
146+
## Day 3
147+
148+
**The solution to the CSV problem will be released after the assignment is due**
149+
150+
<!-- links -->
151+
152+
[Programming Ruby]: http://www.ruby-doc.org/docs/ProgrammingRuby/
153+
[Range]: http://www.ruby-doc.org/core-1.9.3/Range.html
154+
[Regex]: http://www.ruby-doc.org/core-1.9.3/Regexp.html
155+
[Ruby API]: http://www.ruby-doc.org
156+
[gsub]: http://www.ruby-doc.org/core-1.9.3/String.html#gsub-method

0 commit comments

Comments
 (0)