CS 330 Lecture 37 – Ruby Objects
Agenda
- what ?s
- why do I preincrement?
- Ruby symbols
- classes in Ruby
The Final
For the final, you are expected to:
- write code that intelligently shares data via references (C++)
- be able to templatize a given class to increase its reusability (C++)
- generalize functions into higher-order functions that parameterize work (Haskell)
- use pattern matching to “overload” functions (Haskell)
- compose lambda functions (Haskell)
- use map and fold to simplify many algorithms (Haskell)
- reason about the strengths and weaknesses of each language we’ve covered (assembly, shell, C, C++, Haskell, Ruby)
- compose a class using inheritance and mixins (Ruby)
- use blocks to pass code sequences off to higher-order functions (Ruby)
TODO
- Write a question that could appear on the final exam. Derive your question from the topics above. Post in the comments for a participation point, using a name by which I can identity you. (First name and last initial is fine.) Post a second for extra credit. Do not turn in a piece of paper.
Code
wrapper.cpp
#include <iostream>
using std::ostream;
class Integer {
public:
Integer(int i) : i(i) {}
// pre increment
Integer &operator++() {
i += 1;
return *this;
}
// post increment
Integer operator++(int) {
Integer tmp = *this;
i += 1;
return tmp;
}
int get() const {
return i;
}
private:
int i;
};
ostream &operator<<(ostream &out, const Integer &n) {
return out << n.get();
}
int main(int argc, char **argv) {
Integer count1(7);
std::cout << "count1++: " << count1++ << std::endl;
Integer count2(7);
std::cout << "++count2: " << ++count2 << std::endl;
return 0;
}
rpg.rb
#!/usr/bin/env ruby
class Character
def initialize(name, hp, mp, charisma=0, luck=0)
@name = name
@hp = hp
@mp = mp
end
def to_s
"#{@name} [HP: #{@hp} | MP: #{@mp}]"
end
def takeHit(force)
@hp -= force
end
# def mp
# @mp
# end
def mp= new_mp
@mp = new_mp
end
attr_reader :mp, :hp, :name
end
class PotHead
def takeHit(x)
puts "..."
end
end
class Dragon < Character
def ignite(other)
other.takeHit(100)
end
end
class BlackMage < Character
def ice(other)
# other.takeHit(10) if @mp > 0
if @mp >= 5
other.takeHit(10)
@mp -= 5
end
end
def ica(other)
2.times {ice(other)}
end
def icaga(other)
3.times {ice(other)}
end
end
Haiku
class Haiku:
def nsyllables x; [3, 12, 3][x]; end
Perversion