Home > Enterprise >  How to get the puts output to read actual numbers instead of (x,y)
How to get the puts output to read actual numbers instead of (x,y)

Time:02-21

So my written program works, but when I get the output it says, point x,y lies at "insert end". What do I need to change to get the "x,y" to give the digits that are inputted?

puts "Enter the x and y coordinate points:"
x = gets.chomp.to_f
y = gets.chomp.to_f

if x > 0 and y > 0
  puts "point #{"x,y"} lies in the First quadrant"
elsif x < 0 and y > 0
  puts "point #{"x,y"} lies in the Second quadrant"
elsif x < 0 and y < 0
  puts "point #{"x,y"} lies in the Third quadrant"
elsif x > 0 and y < 0
  puts "point #{"x,y"} lies in the Fourth quadrant"
elsif x == 0 and y > 0
  puts "point #{"x,y"} lies at the positive y axis"
elsif x == 0 and y < 0
  puts "point #{"x,y"} lies at the negative y axis"
elsif y == 0 and x < 0
  puts "point #{"x,y"} lies at the negative x axis"
elsif y == 0 and x > 0
  puts "point #{"x,y"} lies at the positive x axis"
else
  puts "point #{"x,y"} lies at the origin"
end    

CodePudding user response:

Use two #{} constructs (one for each variable) to interpolate the two variables like this:

puts "point #{x},#{y} lies in the first quadrant"

#{"x,y"} simply inserts the string "x,y" into the string, which isn't what you want.

Interpolating both variables into the string with a single #{} is possible, but it is a bit more verbose because you have to call to_s twice since x and y are floats. They can't be concatenated as-is with ',' as Ruby will try to convert the string to a float and then complain that it can't.

puts "point #{x.to_s   ','   y.to_s} lies in the first quadrant"

CodePudding user response:

As pointed out "#{value}" interpolates value and your value is the literal "x,y" which is why you get the result you do. If you want more control of how the values are formatted you can do something like this:

formatted_point = "point %.1f, %.1f" % [x,y]

and then use it like this.

puts "#{formatted_point} lies in the First quadrant"

You can find all the details on string formatting here

  •  Tags:  
  • ruby
  • Related