你可能想要map
,如
array = series.map do |num|
但要正确使用它,您将需要调整您的块,以便它返回您想要的数组的值,而不仅仅是打印出来(puts
返回nil
,您不想要这里)。
要将每个单独的数字收集到主数组内的子数组中,而不是puts
, 您想要subarray.push( num )
或类似的 - 有一些等效的语法。然后取而代之(或之后)puts " "
,最后只有subarray
变量(或您所称的任何内容),这将使其成为块的返回值,并将其添加到您的主数组中。你最终会得到一个数组数组。
如果您想探索 Ruby 对象的可能性,我强烈建议您启动irb
并使用methods
命令查看您可以使用它做的所有事情:
irb
1.9.3-p327 :001 > a = [1,2,3,4]
=> [1, 2, 3, 4]
1.9.3-p327 :002 > a.methods.sort
=> [:!, :!=, :!~, :&, :*, :+, :-, :<<, :<=>, :==, :===, :=~, :[], :[]=, :__id__, :__send__, :all?, :any?, :assoc, :at, :chunk, :class, :clear, :clone, :collect, :collect!, :collect_concat, :combination, :compact, :compact!, :concat, :count, :cycle, :define_singleton_method, :delete, :delete_at, :delete_if, :detect, :display, :drop, :drop_while, :dup, :each, :each_cons, :each_entry, :each_index, :each_slice, :each_with_index, :each_with_object, :empty?, :entries, :enum_for, :eql?, :equal?, :extend, :fetch, :fill, :find, :find_all, :find_index, :first, :flat_map, :flatten, :flatten!, :freeze, :frozen?, :grep, :group_by, :hash, :include?, :index, :initialize_clone, :initialize_dup, :inject, :insert, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :join, :keep_if, :kind_of?, :last, :length, :map, :map!, :max, :max_by, :member?, :method, :methods, :min, :min_by, :minmax, :minmax_by, :nil?, :none?, :object_id, :one?, :pack, :partition, :permutation, :pop, :private_methods, :product, :protected_methods, :public_method, :public_methods, :public_send, :push, :rassoc, :reduce, :reject, :reject!, :repeated_combination, :repeated_permutation, :replace, :respond_to?, :respond_to_missing?, :reverse, :reverse!, :reverse_each, :rindex, :rotate, :rotate!, :sample, :select, :select!, :send, :shift, :shuffle, :shuffle!, :singleton_class, :singleton_methods, :size, :slice, :slice!, :slice_before, :sort, :sort!, :sort_by, :sort_by!, :taint, :tainted?, :take, :take_while, :tap, :to_a, :to_ary, :to_enum, :to_s, :transpose, :trust, :uniq, :uniq!, :unshift, :untaint, :untrust, :untrusted?, :values_at, :zip, :|]
这是大量的学习方法!但是,如果您Ruby Array map
在 Google 中输入 eg,您通常会在第一个答案中获得有用的参考。
许多 Ruby 习语都是基于您可以通过将数组方法与块组合来完成的事情,值得花时间进行探索。