Ruby if-else语句

Ruby if-else语句,ruby,conditional,Ruby,Conditional,我被要求: 定义一个名为first_longer_than_second的方法,其中一个参数名为first,另一个参数名为second。如果传入的第一个单词大于或等于第二个单词的长度,则该方法将返回true。否则返回false 这是我提出的代码: def first_longer_than_second(first, second) if first >= second return true; else return false; end end 我

我被要求:

定义一个名为first_longer_than_second的方法,其中一个参数名为first,另一个参数名为second。如果传入的第一个单词大于或等于第二个单词的长度,则该方法将返回true。否则返回false

这是我提出的代码:

def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end
我正在打的电话:

first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true
由于某些原因,在repl.it上,我只得到假输出

我在平台上收到这个错误消息,我实际上是要在平台上完成这个任务的:

expected #<TrueClass:20> => true
     got #<FalseClass:0> => false

Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.

exercise_spec.rb:42:in `block (2 levels) in <top (required)>'
尝试了很多事情,但令人恼火的是坚持做一些看似简单的事情

定义一个名为first_longer_than_second的方法,其中一个参数名为first,另一个参数名为second。如果传入的第一个单词大于或等于第二个单词的长度,则该方法将返回true。否则返回false

您的代码:

def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end
首先,您的代码不符合要求。他们要求比较两个论点的长度。如果条件为:

if first.length >= second.length
def first_longer_than_second(first, second)
  first.length >= second.length
end
请参阅的文档

关于Ruby的语法,分号;后面的语句是不需要的。与Javascript一样,Ruby语句可以使用分号终止,也可以使用换行符终止。分号用于分隔同一行上的两条语句

接下来,与Javascript和许多其他语言一样,您可以直接返回比较结果,而不是将其放入返回true/false的if语句中:

最后一个改进是使它看起来像Ruby,而不是Javascript或PHP:Ruby函数返回它计算的最后一个表达式的值;这使得return关键字在这里显得多余

您的代码应该是:

if first.length >= second.length
def first_longer_than_second(first, second)
  first.length >= second.length
end

如果传入的第一个单词大于或等于第二个单词的长度-我看不到在代码中使用第二个单词的长度。另外,从测试案例来看,你似乎应该比较第一个参数的长度,而不是它的值!谢谢大家!@axiac给出答案,我会同意,您不需要if语句,只需要first.length>=second.length。感谢您提供的所有添加信息!真的对我的未来很有帮助!!