|
As we saw earlier with #to_ary some of these conversion methods are used internally to Ruby, these are the strict conversion methods, but can also be thought of as the implicit conversion methods. They can be used implicitly because they are strict.
These are used all over the place within Ruby, but as an example #to_int is used to convert the argument to Array#[] to an int, and #to_str is used by raise when its argument isn’t an Exception.- class Line
- def initialize(id)
- @id = id
- end
- def to_int
- @id
- end
- end
- line = Line.new(2)
- names = ["Central", "Circle", "District"]
- names[line] #=> "District"
- class Response
- def initialize(status, message, body)
- @status, @message, @body = status, message, body
- end
- def to_str
- "#{@status} #{@message}"
- end
- end
- res = Response.new(404, "Not Found", "")
- raise res #=> RuntimeError: 404 Not Found
复制代码 |
|