Thinking Like Programmer - RubyGuides
Thinking Like Programmer - RubyGuides
1 Learning Ruby
2 Understanding Variables
7 Object-Oriented Programming
Download eBook
https://www.rubyguides.com/ruby-tutorial/thinking-like-programmer/ 3/12
03/04/2024, 12:16 Thinking Like a Programmer - RubyGuides
To review:
Variables
Strings, Arrays & Hashes
If statements
Loops
With these 4 things, plus Ruby built-in commands (we call these
methods) you have all the power of Ruby in your hands.
When you know what you want write a list of steps in plain English.
Here’s an example:
Let’s say that I have a folder full of mp3 files & I want to print them
https://www.rubyguides.com/ruby-tutorial/thinking-like-programmer/ 4/12
Let s say that I have a folder fullThinking
03/04/2024, 12:16
of mp3 files & I want to print them
Like a Programmer - RubyGuides
Now:
To turn these steps into code you’ll need to get creative & use
everything you have learned about Ruby.
Most of the time the error message has information to help you
fix the problem.
There are two things you want to look for in an error message:
This tells you that the error started at the exception.rb file, on line 7 .
https://www.rubyguides.com/ruby-tutorial/thinking-like-programmer/ 7/12
03/04/2024, 12:16 Thinking Like a Programmer - RubyGuides
This means you tried to use something with the name of bacon , but
Ruby can’t find anything with that name.
It’s possible that you made a typo, or maybe you forgot to create that
variable.
1. letters[5]
1. letters[5].foo
1. if letters[5]
2. letters[5].foo
3. end
If you find another error that you don’t understand you can drop it
into Google & you’ll find some hints on how to fix it.
If you are starting with a string then string methods will be useful.
If you are starting with an array then look for an Array method that
does what you want.
You can find all the available methods using the Ruby documentation.
For example:
https://www.rubyguides.com/ruby-tutorial/thinking-like-programmer/ 9/12
03/04/2024, 12:16 Thinking Like a Programmer - RubyGuides
If I have a string like “a,b,c,d” & I want to break it down into an array
of characters without the commas.
A quick test in irb reveals that this is what we were looking for!
If you don’t know what kind of object you are working with you can
use the class method.
Example:
1. "apple".class
2.
3. # String
ME T H O D CO NV E RSI O N
https://www.rubyguides.com/ruby-tutorial/thinking-like-programmer/ 10/12
03/04/2024, 12:16 Thinking Like a Programmer - RubyGuides
Both split & join take an optional parameter where you can specify
the separator character.
Example:
1. "a-b-c".split("-")
2.
3. # ["a", "b", "c"]
Ruby Gems
Sometimes what you want to do is more complicated than this.
You may want to pull down data from a website & find images to
download.