Ruby类方法范围。为什么方法是私有的?

时间:2014-07-06 02:40:25

标签: ruby arrays class oop methods

我的简短应用的要点是从用户的输入中找到由七位数字(超过一百万)组成的价格。

我写了这个:

class Price
  attr_accessor :data

  def initialize(str)
    @data = str
  end

  def lookup
    @data.select do |i|
      i[/\d{1,7}+/]
    end
  end

  def print_and_max
    puts "Here comes the maximum"
    # some code and voila
  end

end

prices = gets.to_a
str = Price.new(prices)
print str.lookup

我收到此错误:

price.rb:21:in `<main>': undefined method `to_a' for "124789358124 12478912578915 50000000 50204500\n":String (NoMethodError)

好的,让我们再试一次:

class Price
  attr_accessor :data

  prices = []

  def initialize(str)
    @data = str
  end

  def lookup
    @data.select do |i|
      i[/\d{1,7}+/]
    end
  end

  def print_and_max
    puts "Here comes the maximum"
    # some code and voila
  end

end

prices = gets
str = Price.new(prices)
print str.lookup

然后结果就是这样:

price.rb:11:in `lookup': private method `select' called for "124789358124 12478912578915 50000000 50204500":String (NoMethodError)

似乎我完全不理解Ruby中的方法范围。主要思想是抓住由空格或其他东西分隔的数字串,然后将其转换为数组并打印出来。将输出最大值的写入方法是可选的。为什么选择方法是私有的?我试图将我的Price类与Array关联,但是select方法仍然是私有的。

我试过这个:

prices = [125215213]

@data可以访问:

irb(main):028:0* str.data
=> [125215213]

.lookup不是:

irb(main):029:0> str.lookup
TypeError: no implicit conversion of Regexp into Integer
    from (irb):11:in `[]'
    from (irb):11:in `block in lookup'
    from (irb):10:in `select'
    from (irb):10:in `lookup'
    from (irb):29
    from /Users/shu/.rbenv/versions/2.0.0-p481/bin/irb:12:in `<main>'
irb(main):030:0> 

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您需要更改此行:

price = gets

到此:

price = gets.chomp.split(" ")

这将把字符串拆分成一个数组,在它找到的每个“”处将它分开。并且chomp将删除在用户输入输入后添加的换行符。

答案 1 :(得分:0)

如果用户输入如下所示: &#34; 124789358124 12478912578915 50000000 50204500&#34;

然后你可以把它变成这样的数组:

prices = gets.split

split是一个String类方法,它将文本块拆分为数组元素。默认情况下它会在空格上分割,但是如果你没有在空格上分割(你看起来像是这样),你可以传递一个参数。

相关问题