Question

Here is an example:

@current_day = 0
@current_time = 100

  def calc_day(amount, type = :add)
    calc_with = type == :add ? "+" : "-"

    @current_day = eval("#{@current_day} #{calc_with} (( #{@current_time} #{calc_with} #{amount}) / 1440)")
  end

  calc_day(:add, 2440)

  p @current_day

You could write the method above this way also:

def calc_day(amount, type = :add)
  if type == :add
    @current_day = @current_day + ((@current_time + amount) % 1440)
  else
    @current_day = @current_day - ((@current_time - amount) % 1440)
  end
end

My question is if there are ways not to use eval, but also dont have to write the whole expression twice with the + and - symbols be the only difference.

Was it helpful?

Solution 2

Use send to dynamically use + or - in your calculations:

def calc_day(amount, type = :add)
  calc_with = type == :add ? "+" : "-"

  @current_day = @current_day.send(calc_with, @current_time.send(calc_with, amount) % 1440)
end

OTHER TIPS

You can try sth like this:

def calc_day(amount, type = :add)
  method_names = {add: :+, subtract: :-}
  method = method_names[type] || raise 'Unknown calculation type'
  @current_day = @current_day.send(method,  (@current_time.send(method, amount) % 1440)
end

You can try multiplying with -1...

def calc_day(amount, type = :add)
  type_op = (type == :add) ? 1 : -1
  @current_day = @current_day + (type_op)*((@current_time + (type_op*amount)) % 1440)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top