Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby类方法作用域。为什么方法是私有的?_Ruby_Arrays_Class_Oop_Methods - Fatal编程技术网

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

Ruby类方法作用域。为什么方法是私有的?,ruby,arrays,class,oop,methods,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"

我的短应用程序的主要目的是从用户输入中找出由七位数(大于一百万)组成的价格

我写道:

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)
结果是这样的:

price.rb:11:in `lookup': private method `select' called for "124789358124 12478912578915 50000000 50204500":String (NoMethodError)
似乎我完全不理解Ruby中的方法范围。其主要思想是获取由空格或其他内容分隔的数字字符串,然后将其转换为数组并打印出来。输出最大值的写入方法是可选的。为什么选择方法是私有的?作为一个孩子,我试图将我的Price类与Array关联起来,但select方法仍然是私有的

我试过这个:

prices = [125215213]
@可访问数据:

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> 
irb(main):029:0>str.lookup
TypeError:没有将Regexp隐式转换为整数
from(irb):11:in`[]'
from(irb):11:in“查找中的块”
发件人(irb):10:在“选择”中
from(irb):10:in“lookup”
来自(irb):29
from/Users/shu/.rbenv/versions/2.0.0-p481/bin/irb:12:in`'
irb(主要):030:0>

我做错了什么?

您需要更改此行:

price = gets
为此:

price = gets.chomp.split(" ")

这将把字符串拆分为一个数组,在找到的每个“”处将其分隔。和chomp将删除在用户输入其输入后添加的换行符。

如果用户输入如下所示: “124789358124 12478912578915 50000000 50204500”

然后可以将其转换为如下数组:

prices = gets.split

split是一个字符串类方法,它将文本块拆分为数组元素。默认情况下,它是按空格分割的,但如果不按空格分割(看起来是这样),则可以向它传递一个参数。

您的主要问题是试图将字符串视为数组。听起来您需要的帮助是正确解释错误消息。你的猜测不太准确。
prices = gets.split