我是 Ruby 的新手。我在上大学,刚刚上了一门涵盖常规 c 语言的编程类(class)。我类的期末项目是一个 slop intercept 项目,这很容易,但我必须对所有事情都使用函数,例如:
#include <stdio.h>
#include <math.h>
int get_problem(int *choice){
do {
printf("Select the form that you would like to convert to slope-intercept form: \n");
printf("1) Two-Point form (you know two points on the line)\n");
printf("2) Point-slope form (you know the line's slope and one point)\n");
scanf("%d", &*choice);
if (*choice < 1 || *choice > 2){
printf("Incorrect choice\n");}
}while (*choice != 1 && *choice !=2);
return(*choice);
}
...
int main(void);
{
char cont;
do {
int choice;
double x1, x2, y1, y2;
double slope, intercept;
get_problem (&choice);
...
我还有几个函数可以完成整个程序。我找到了一份新工作,我需要开始学习 Ruby,所以对于我的第一个项目,我想将这个程序转换成 Ruby,现在我可以简单地摆脱这些功能,而无需方法或过程就可以运行它。我想知道是否可以做同样的事情,定义一个方法,然后在不提供输入的情况下调用该方法,但取回存储在该方法中的变量。是否可以使用方法或过程。这是我到目前为止使用 proc 的一些内容。
get_problem = Proc.new {
begin
puts "Select the form that you would like to convert to slope-intercept form: "
puts "1) Two-Point form (you know two points on the line)"
puts "2) Point-slope form (you know the lines slope and one point)"
choice = gets.chomp.to_i
if (choice < 1 || choice > 2)
puts "Incorrect choice"
end
end while (choice != 1 && choice !=2)
}
....
begin
get_problem.call
case choice
when 1
get2_pt.call
display2_pt.call
slope_intcpt_from2_pt.call
when 2
get_pt_slope.call
display_pt_slope.call
intcpt_from_pt_slope.call
现在我知道我可能完全错了,但我想我会试一试。我把它作为以前的方法
def get_problem(choice)
....
end
....
get_problem(choice)
....
我缺少一些基本的东西吗?如您所见,我在 c 中使用了指针,并且必须在 main 中初始化变量。
感谢您花时间帮助我。 罗伯特
最佳答案
您不能在 Ruby 中传递指向变量的指针,但我认为您不需要这样做来完成您想要做的事情。试试这个:
def get_problem
puts "Select the form that you would like to convert to slope-intercept form: "
puts "1) Two-Point form (you know two points on the line)"
puts "2) Point-slope form (you know the lines slope and one point)"
loop do
choice = gets.chomp.to_i
return choice if [1, 2].include? choice
STDERR.puts "Incorrect choice: choose either 1 or 2"
end
end
choice = get_problem
puts "The user chose #{choice}"
这定义了一个方法 get_problem
,它循环直到用户选择 1
或 2
,并返回他们选择的数字,您可以存储该数字在顶级变量 choice
中。
关于Ruby 可以像 c 调用函数那样调用方法或 proc 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15351767/