Let's say that I plan to write a horse race betting application, and I want a RaceResult
class that can have four discrete values: Win
, Place
, Show
and the "null object" class Lose
.
I come to Ruby from a C# background, and I would normally use an enum
for this, or perhaps a series of static readonly fields created by a private constructor, like so:
public class RaceResult {
public static RaceResult Win = new RaceResult(1);
// ...
private int lowestPositionToWin;
private RaceResult(int position) {
lowestPositionToWin = position;
}
private bool PaysOut(int placement) {
return placement <= lowestPositionToWin; // logic may be flawed here
}
}
If the classes get too complicated, I'd refactor to use a Strategy pattern.
What is a good Ruby approach to solving this requirement? Can I create a class that can only have four instances? I'm having trouble phrasing a Google query to find the information I'm looking for.
EDIT: In the first answers, I've gotten some good ways to handle the case where I just want a named primitive values. However, if I'm interested in extending its behavior, I'd need a custom class. Is there a way I could modify the constant approach to use a class?