0

I am learning Ruby using codecademy and the current exercise tells the user to :

Define two methods in the editor:

A greeter method that takes a single string parameter, name, and returns a string greeting that person. (Make sure to use return and don't use print or puts.)

A by_three? method that takes a single integer parameter, number, and returns true if that number is evenly divisible by three and false if not. Remember, it's a Ruby best practice to end method names that produce boolean values with a question mark.

Based on that I came up with some code but it doesn't work and I do not know how to fix it or what I am missing. Any push in the right direction is greatly appreciated! Here is my code :

def greeter (name)

name = gets.chomp
return "Hi there #{name} sucka!"
end

def by_three(number)

number = gets.chomp
if number % 3 == 0
return true
else return false
end
4

4 回答 4

1

考虑这样的事情:

def greeter(name)
  "Hi there #{name}!"
end

def by_three?(number)
  number % 3 == 0
end

你可以检查这些irb

1.9.3p327 :010 >   greeter 'joe'
 => "Hi there joe!" 
1.9.3p327 :011 > by_three? 9
 => true 
1.9.3p327 :012 > by_three? 10
 => false 

笔记:

在中,除非绝对必要,否则ruby通常不使用,因为在方法中执行的最后一个表达式的结果会自动作为方法的值返回。return

此外,我对您正在处理的问题的解释看起来像是希望您的方法获取参数,因此我删除了gets从标准输入读取的调用,而是期望方法对传递给它的参数进行操作。(虽然我在阅读 codeacademy 问题时肯定是错的。)

于 2013-05-04T02:48:21.257 回答
0
def by_three(number)
   number = gets.chomp
   if number.to_i % 3 == 0
      return true
   else return false
end

您忘记将数字转换为整数,这就是代码不起作用的原因。

于 2013-05-04T02:47:02.683 回答
0
def by_three?(number)
    if !number
        number = gets.chomp
    end

    if ("" << number.to_s) =~ /^(\d)+$/
        number.to_i % 3 == 0
    else
        false
    end 
end

我认为这是一个很好的答案。

于 2013-05-04T04:23:21.663 回答
0
def greeter(name)
  return ("greeting " + name)
end 

greeter("rahul")

def by_three?(number, i)

    if number % 3 == i
        i % 2 == 0 
        return "true"
    else 
        return "false"
    end

    end 
    by_three?(12,1)

这可能会有所帮助

于 2014-01-17T07:08:36.933 回答