Ruby:字符串比较问题 [英] Ruby: String Comparison Issues

查看:50
本文介绍了Ruby:字符串比较问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Ruby,除了一个小的字符串比较问题外,我很享受几乎所有的东西.

I'm currently learning Ruby, and am enjoying most everything except a small string comparason issue.

answer = gets()

if (answer == "M")  
    print("Please enter how many numbers you'd like to multiply: ")   
elsif (answer. == "A")  
    print("Please enter how many numbers you'd like to sum: ")  
else  
    print("Invalid answer.")  
    print("\n")    
    return 0  
end

我正在做的是我正在使用 gets() 来测试用户是否想要乘以他们的输入或添加它(我已经测试了两个函数;它们工作),后来我得到了更多的输入函数和浮动翻译(也适用).

What I'm doing is I'm using gets() to test whether the user wants to multiply their input or add it (I've tested both functions; they work), which I later get with some more input functions and float translations (which also work).

结果是我输入 A 后得到无效答案".M 也会发生同样的情况.

What happens is that I enter A and I get "Invalid answer."The same happens with M.

这里发生了什么?(我也用过 .eql? (sp),它也返回 bubcus)

What is happening here? (I've also used .eql? (sp), that returns bubcus as well)

推荐答案

gets 返回输入的整个字符串,包括换行符,因此当他们输入M"并按回车键时,您会返回该字符串是 "M\n".要去掉尾随的换行符,请使用 String#chomp,即将第一行替换为 answer = gets.chomp.

gets returns the entire string entered, including the newline, so when they type "M" and press enter the string you get back is "M\n". To get rid of the trailing newline, use String#chomp, i.e replace your first line with answer = gets.chomp.

这篇关于Ruby:字符串比较问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆