Optional parameters: Difference between revisions

add Ruby
(BASIC added (Beta BASIC, SAM BASIC))
(add Ruby)
Line 332:
"" "q" "z"
>>> </lang>
 
=={{header|Ruby}}==
Ruby does provide a mechanism to specify default values for method arguments:
<lang ruby>def tablesort(table, ordering=:sort_proc, column=0, reverse=false)
# ...</lang>
However, you cannot pass named parameters: if you want to pass "reverse=true", you must also give values for ordering and column.
 
The idiomatic way in Ruby is to pass a hash or name=>value pairs as method arguments, like this:
<lang ruby>def tablesort(table, *options)
# default values
opts = {"ordering" => :sort_proc, "column" => 0, "reverse" => false}
 
# now, merge in user's options
opts.merge!(options[0]) if options
 
# ... rest of code, for example
opts.each_pair {|name, value| puts "#{name} => #{value}"}
end
 
tablesort(data, "reverse" => true, "column" => 3)</lang>
 
=={{header|Tcl}}==
Anonymous user