Messages with Methods in Ruby
You hear it all the time when reading about Ruby: everything is an object. Objects in Ruby communicate with other objects by passing "messages" back and forth to one another. Well, those messages are passed by using these things called methods, and Ruby let's us easily see all the methods available on any object at any given time.
Quickie
Let's take a look at what all this means. Open up a repl:
> "goo".class
=> String
> "goo".class.superclass
=> Object
We've created a string goo on the fly and looked up it's class and superclass. There's all the proof we need that we are dealing with an object. To see what methods we can call on this string object we can do:
> "goo".methods
Pretty cool. Want to look up the methods on your object's class? No problem:
> "goo".class.methods
What if you don't have an instance of a class handy and just want to see what instance methods exist for a given class?
> String.instance_methods
This list of methods includes all the methods an instance of the String class inherits. Maybe you only want the methods declared on a string?
> String.instance_methods.count
=> 188
> (String.instance_methods - Object.instance_methods).count
=> 120
Either way, that gives us a long list of methods to play with. In fact, let's try one out together right now. I see a reverse method in there, so let's see what that does:
> "goo".reverse
=> "oog"
> "goo".reverse.upcase
=> "OOG"
Good times. What's this to_yaml do?
> ""goo"".to_yaml
=> ""--- goo\n...\n""
Are you finding these lists of methods too difficult to sort through?
> String.instance_methods.sort
# alphabetical order
> String.instance_methods.grep /^re/
# returns instance methods that start with 're'
Ruby is pretty declarative and to the point, and playing around with methods like this quickly demonstrates that point. There is something that just feels right about writing code in order to learn more about code. It is the little things like this that can make it so enjoyable to work with.
(▰˘◡˘▰)
Leave Messages with Methods in Ruby to:
Read more #ruby posts
Best Posts From davidpm
We have not curated any of davidpm's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From davidpm
- Disabling dangerous redis commands in Production redux
- Heuristics on the Practice of Programming
- Git Interactive Rebase to Alter Commits
- Dropping Into B-trees
- Create a command-line gem from scratch with Thor (part two)
- Create a command-line gem from scratch with Thor
- Blockchain Proof of Concept
- SQL Cheat Sheet
- Bootstrap with Rails and Postgres
- REGEX Multiline Anchors
- Rspec Config
- Rails MIME Types
- Messages with Methods in Ruby
- CPUs