Question

How would I coerce the behavior of irb to treat variable identifiers as strings when used in method signatures?

I am trying to create a irb based calculation tool and I want to reduce the typing of users who use this tool in the irb shell. Assume my users are not ruby programmers or know much about the syntax of ruby. The may have some facility with the command line.

I have a file

calculator.rb

inside this file is

def calculate(value, units)

... some logic

end

I instruct the user to fire up irb like so

irb -r path/to/calculator.rb

I instruct the user to type

calculate(10, inches)

get return value in irb

how can I do this without requiring the user to understand that they have to wrap the second parameter in quotation marks. In other words I don't want the user to have to type

calculate(10, "inches")

is it possible to cast the user input as a string instead of a variable identifier before it is passed to my method inside my script? Maybe what I want to do is not possible without fundamentally breaking irb shell?

Was it helpful?

Solution

If this is for non-programmers how about using puts and gets?

def calculate
  puts "Which number would you like to convert?"
  number = gets.to_i
  puts "What do you want to convert it to?"
  type = gets
  # your conversion logic
  puts result
end

OTHER TIPS

You can actually do it the way you requested using method_missing. Any matching units will get converted to strings instead of raising exceptions.

SO_CALC_UNITS = %w[inches feet yards meters parsecs]
def method_missing(method)
  if SO_CALC_UNITS.include?(method.to_s)
    method.to_s
  else
    super(method)
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top