Ruby Arrays. Hashes and Ranges (Part 4)
You now have an array named “Spaghetti_sauce”, that contains those elements. You can also assign multiple values into several elements with the following instruction:
Spaghetti_sauce = %w[ground pork, ground beef, tomato sauce, garlic, pepper, onions, salt, olive oil]
You end up with the same array we started with that has all the elements stored within it. There are a couple of easy ways to use and manipulate arrays such as for checking if it is empty, you simply use the following command:
Spaghetti Sauce.empty?
Checking for the total number of elements you do:
Spaghetti_sauce.size
or
puts Spaghetti_sauce.size
You can also delet elements from arrays with the delete nethod :
Spaghetti_sauce.delete “ground beef”
Looking for the first or last element you use the “.first” and “.last” method shown below :
Spaghetti_sauce.first
Spaghetti_sauce.last
If you have an unknown data structure and you want to check if it is indeed an array, you simply use the “.type” method. The “class” method is better than the “.type” method for it gives you a verbose warning.
puts Spaghetti_sauce.type (to check if the array is indeed an array)
puts Spaghetti_sauce.class (more verbose way of checking that returns an error message)
arrays also have the nift anility to store elements of different data types like characters, strings and numbers shown below:
sauce = [ 'h', 'and', 'r', '@', 20]
Comments are off for this post
