+ and - are called operators. We can use them with the array of fruits just like we can use them with numbers.
Everything in Ruby has a class. Type this into IRB:
These are the three data types introduced so far: Fixnum (numbers), String (text), and Array (lists).
Each class has different methods that can be used on instances
of that class. If you're not quite sure what an instance is, this page
on Ruby classes might
You can see all the methods available for an object:
And you can call multiple methods in a row:
In fruit.methods.sort above, fruit.methods returns an array, and
.sort sorts that array. It's exactly like this, but without the array
array = fruits.methods
Arrays have a method called each which iterates through the list running code on each item.
fruits.each do |fruit|
This takes the first item from the fruits array ("strawberry"),
assigns it to the variable fruit, and runs the code between do and
end. Then it does the same thing for each other item in the list. The
code above should print a list of the fruits.
A conditional runs code only when a statement evaluates to true.
if my_variable > 1
This prints YAY! if the value stored in my_variable is greater than 1.
Try changing the > in the conditional to a <.
You can also make your own methods:
word + "s"
Methods take parameters, which are the variables they work on. In this case, we made a method called pluralize that takes one parameter, a word.
Methods can also return data. In this case, pluralize returns the word with an 's' added to the end of it. In Ruby, methods return whatever the last line of the method evaluates to.
This is an optional practice question if you want to brush up on your Ruby. Feel free to skip it! Or talk to your TA if you get stuck, or discuss your solution once you have completed the checkpoint.
Write some Ruby that prints out the names of the people in your group.
Start by opening up irb.
Create the names as strings in an array.
Store that array to a variable.
Then use the .each method on the stored array to loop through each of the names.