how to learn ruby
the best way to learn how to code is to actually code. so please go ahead and copy the examples from the github repository that will be provided and follow along the example. Experiment in the editor by typing, by modifying the examples and executing the examples and seeing what happens. That’s the only way to learn how to code.
Ruby basics
Ruby is an Object-Oriented Language
Ruby is a genuine object-oriented language, and pretty much everything in Ruby is an object.
for example the number 5
in ruby is an object of the class called Fixnum
1 | irb(main):011:0* 5 |
flow of control in Ruby
tips:
false and nil objects are false
everthing else is true include 0
triple equal ==> === is called the case equality operator because it is used in precisely this case!
most of the time triple equals just delegates to a double equals, so it’s almost like a super set of a double equals.
3 flavors
- regular expression
- double equals
- comparing the value class
Functions and Methods
- Technically, a function is defined outside of a class and a method is defined inside a class.
- In Ruby, every function/method has at least one class it blongs to. Not always written inside a class.
**Methods: **
Methods are invoked by sending a message to an object.
- Parentheses(“()”) are optional both when defining and calling a method
- No need to declare type of parameters
- Can return whatever you want
- return keyword is optional(last executed line returned)
- Method names can end with:
- ‘?’-predicate methods
- ‘!’-dangerous side-effects
- Methods can have default arguments
Blocks
- Chunksof code
- Enclosed between either curly braces({}) when block content is single line or the keywords
do
andend
when block content spans multiple lines. - Passed to methods as last “parameter”
- Enclosed between either curly braces({}) when block content is single line or the keywords
- Coding with blocks
- two ways to configure a block in your own method
- Implicit
- use `block_given?’ to see if block was passed in
- use ‘yield’ to “call” the block
- Explicit
- use
&
in front of the last “parameter” - use call method to call the block
- use
- Implicit
- two ways to configure a block in your own method
files
- read file:
1
2
3
4
5
6
'test.txt') do |line| File.foreach(
irb(main):002:1* puts line
p line
p line.chomp
p line.split
end
write file
1
2
3
4
5# override the file
"test.txt", "w") do |file| File.open(
irb(main):008:1* file.puts "one line"
"second line" file.puts
end