ruby - Removing a Hash -


this question has answer here:

so works, except 1 problem, comes under method calculate. i'm using tdd program , telling me works except when calculate passed (0,3,5) inserts 5 options, when should default addition , add numbers 0, 3, 5 since options part blank. how make options deleted, or passed true if there nothing there code passes without add: true or subtract: true?

def add(*numbers)   numbers.inject(0) { |sum, number| sum + number } end  def subtract(number1,*additionalnums)   number1-add(*additionalnums) end  def calculate(*addsubtract, options)   result = add(*addsubtract) if options[:add]   result = subtract(*addsubtract) if options [:subtract]   result = calculate.delete(-1) if options.is_a?(symbol)   result end 

you use named parameters (aka 'keyword arguments'), introduced in ruby 2.0:

   def doit(*args, op: :+)      args.reduce { |t,e| t.send(op, e) }    end     doit(1, 2, 3)           # =>  6       doit(1, 2, 3, op: :-)   # => -4      doit(1, 2, 3, op: :*)   # =>  6      doit(1.0, 2, 3, op: :/) # =>  0.166.. 
  • in calls doit, not smileys.
  • the default value of op given op: :+. that's shorthand :op => :+. (not rubyists approve of former terminology.) looks element of hash, eh? in fact, that's precisely is.
  • you don't have use object#send, of course. example might employ object#case, particularly if want pass methods other big four. in case may prefer pass strings, rather symbols:
    def doit(*args, op: '+')      case op      when '+', '-', '*'. '/'        args.reduce { |t,e| t.send(op.to_sym, e) }      when 'min'        args.min      when 'avg'        args.any? ? args.reduce(:+)/args.size.to_f : 0.0      when 'and_so_on'        ...      end    end 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -