The Ruby Way: Solutions and Techniques in Ruby Programming (3rd Edition) (Addison-Wesley Professional Ruby Series)

The Ruby Way: Solutions and Techniques in Ruby Programming (3rd Edition) (Addison-Wesley Professional Ruby Series)

Author:Hal Fulton & André Arko
Language: eng
Format: mobi
Publisher: Pearson Education
Published: 2015-02-10T22:00:00+00:00


def initialize(name)

@name = name

end

# ...

def to_s

"Pet: #@name"

end

end

Other methods (such as the String concatenation operator +) are more picky; they expect you to pass in something that is really pretty close to a String. In this case, Matz decided not to have the interpreter call to_s to convert non-string arguments because he felt this would lead to too many errors. Instead, the interpreter invokes a stricter method, to_str. Of the built-in classes, only String and Exception implement to_str, and only String, Regexp, and Marshal call it. Typically when you see the runtime error TypeError: Failed to convert xyz into String, you know that the interpreter tried to invoke to_str and failed.

You can implement to_str yourself. For example, you might want to allow numbers to be concatenated to strings:

Click here to view code image

class Numeric



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.