Home > Software engineering >  How to transform the result of an iterator into an array in Ruby
How to transform the result of an iterator into an array in Ruby

Time:12-22

I want to know how to transform the results of an iterator into an array. I have presented two options below, and both run, but yield the result in the wrong format.

This is the result I am getting vs what is expected.

enter image description here

I am trying to transform the iterator results into an array with Array(), but it does not work.

I tried:

  1. Block code with .keep_if methods
  2. for if conditionals with Array() to make the transformation.

What I expect:

An array of non-negative integers. The input (l) is an array of random integers and strings.

My code options are as follows:

Option 1:

def filter_list(l)
  l.delete_if {|li| li.class ==String || li<0}
  puts l
end

Option 2:

def filter_list(l)
  arr=[]
  for i in l
    if i.class == Integer && i>=0
      arr1=arr.push(i)
    end
  end
  puts Array(arr1)
end

Why don't the above options work?

CodePudding user response:

Why don't the above options work?

You have a syntax error here:

Def filter_list(l)
↑

Method definitions use the def keyword with a lower-case d. What you have written here will be interpreted as a method call to a method named Def, passing filter_list(l) as an argument, i.e. that code will be interpreted as

self.Def(filter_list(l))

Which then means that Ruby is not expecting to see an end keyword.

CodePudding user response:

To output the result in the expected format just use p instead of puts.

From the docs of puts

[...] If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its to_s method. [...]

Whereas the p method doesn't call to_s but inspect before printing the output:

For each object, directly writes obj.inspect followed by a newline to the program's standard output.

The default string representation, returned by inspect for an array, looks like your expected output.

  • Related