Learning Ruby and Rails Notes
Strings
Strings are surrounded in quotes. For example, "David" is a string.
A complete list of Ruby string methods is here.
.reverse
"David".reverse
>> "divaD"
.length
"David".length
>> 5
.strip
Removes white space around a string.
"David ".strip
>> "David"
multiplication
"David" * 5
>> "DavidDavidDavidDavidDavid"
Converting Object Types
.to_s – converts to strings
.to_i – converts to integers
.to_a – converts to arrays
Arrays / Lists
Use brackets [].
[12, 47, 35]
.max
[12, 47, 35].max
>> 47
Hash / Dictionary / Associative Array
A hash is when you want to associate one thing with something else, like a dictionary. These are called Key, Value pairs.
Hashes use curly braces {}.
food["Fish"] = :yum
food["Dog"] = :yuck
food["Beef"] = :delicious
food
>> {"Fish" => :yum, "Dog" => :yuck, "Beef" => :delicious}
rating
food.keys
>> ["Fish", "Dog", "Beef"]
Blocks
Using the above example of food, you may use a block like the following to tally your results.
books.values.each { |rate| ratings[rate] += 1 }
>> [:yum, :delicious, :yuck]
ratings
>> {:yum => 1, :yuck => 1, :delicious => 1}
Another example of using a block:
5.times {print "Yes!"}
>> Yes!Yes!Yes!Yes!Yes!
Classes
String, Array, Hash are all examples of Classes.
Creating a class
class BlogEntry
attr_accessor :title, :time, :fulltext, :mood
end
attr_accessor is how you define variables, or in this case attributes attached to a class.
Let’s start a new entry.
entry = BlogEntry.new
entry.title = "Hello world!"
entry.fulltext = "Yes this is my first post!"
entry.mood = :sick
entry.time = Time.now
The initalize Method
Using the initalize method you won’t have to type the time every post.
class BlogEntry
def initalize( title, mood, fulltext )
@time = Time.now
@title, @mood, @fulltext = title, mood, fulltext
end
end
Important things to notice
Outside the class we use accessors: entry.time = Time.now. But inside we use instance variables: @time = Time.now.
Trackbacks & Pingbacks