Ruby类方法作用域.为什么方法是私有的



这个简短的应用程序的主要目的是从用户的输入中找到由7位数(大于100万)组成的价格。

我写的是:

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 50204500n":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]

。查找不是:

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> 

我做错了什么?

如果用户输入如下:"124789358124 12478912578915 50000000 50204500"

然后你可以把它变成一个数组,像这样:

prices = gets.split

split是一个String类方法,用于将文本块拆分为数组元素。默认情况下,它根据空白进行分割,但如果您不根据空白进行分割(看起来像是这样),则可以向它传递一个参数。

你需要改变这一行:

price = gets

:

price = gets.chomp.split(" ")

这将把字符串分割成一个数组,在它找到的每个" "处将其分开。而chomp,将删除用户输入后添加的换行符。

最新更新