Functions in ruby work and look a lot like they do in javascript. When we covered loops, we saw that ruby did not inlcude curly braces as a way to contain logic. The same is true for ruby's functions.
We will also see that import content from other files.
Rather than using curlies, we use indentation and the end keyword to contain our logic.
So in javascript, a typical function will look like this:
function math(num1, num2) {
return num1 + num2
}Whereas in ruby, the same function looks like:
def math(num1, num2)
return num1 + num2
endRemember how we require files or packages in Node? We can actually use the exact same keyword here!
In Javascript, it looked like this
require("./helpers")In ruby, it's almost exactly the same!
require "./helpers" If we had functions written in the helpers file referenced above, we could simply refer to them as though they were in the file we're currently working in. In other words, no need for a helpers.function_name. We could simply refer to function_name as though it was defined in the file we're currently working in.
-
In this exercise, you'll notice you have two files to work in rather than the single prompt.rb you're used to.
helpers.rbwill host all of the functions we'll write in this exercise. They'll be invoked inprompt.rb. Paste your shop hash inside ofprompt.rb. -
Require
helpers.rbinprompt.rb. -
In
helpers.rb, write a function calledprint_spaces, which prints 20 equals signs ("="). -
In
helpers.rb, write a function calledconvert_items_to_obj, which takes an hash and a key as arguments.convert_items_to_objconverts each item in your items array into a hash. Each hash should have a key ofname, which points to the item originally in that spot in the array, a key ofid, which points to a unique id, a key ofsell_price, which points to the value 2.50 (a float), and a key ofcost, which points to the value 1.15 (a float). -
In
helpers.rb, write a function calledadd_props, which takes a hash, a key and a value as arguments.add_propsadds the given key to the given hash. The given key points to the given value. Your function should also print out the value it add to the given hash. -
In
helpers.rb, write a function callednet_profit, which takes in an array as an argument.net_profitcalculates the sum of every item's sell_price, and every item's cost. It subtracts the total cost from the cumulative sell price, and returns a net profit. -
In
helpers.rb, write a function calledgoodbye, which takes a name (string) as an argument.goodbyewrites a farewell message addressed to the given name. -
Invoke each function from
helpers.rbinprompt.rb. Each function should be invoked in between to invocations of theprint_spacesfunction.
- Any time a hash is taken as an argument, pass in your own store as that argument.
- for
add_props, add a store owner with your own name as the value. - Print out (or use
puts) thenet_profitfunction. - Pass in the added store owner key as an argument to your
goodbyefunction.