ruby - What are options hashes? -
will please explain options hashes? working through ruby course testfirst.org. exercise 10 (temperature_object) requires knowledge of options hashes.
options hash nice concept enabled feature of ruby parser. say, have method required arguments. may pass optional arguments. on time may add more optional arguments or remove old ones. keep method declaration clean , stable, can pass optional arguments in hash. such method this:
def foo(arg1, arg2, opts = {}) opts.to_s # return string value of opts end
so has 2 required values , last argument default value of hash. if don't have optional arguments pass, call this:
foo(1, 2) # => "{}"
if have optional, call this:
foo(1, 2, {truncate: true, redirect_to: '/'}) # => "{:truncate=>true, :redirect_to=>\"/\"}"
this code idiomatic ruby parser allows omit curly braces when passing hash last argument method:
foo(1, 2, truncate: true, redirect_to: '/') # => "{:truncate=>true, :redirect_to=>\"/\"}"
if use rails, example, you'll see options hashes everywhere. here, opened random controller in app:
class productscontroller < applicationcontroller before_filter :prepare_search_params, only: :index # ^^^^^^^^^^ options hash here
so, in short: options hash argument of method located last , has default value of {}
. , pass hashes (hence name).
Comments
Post a Comment