-1

so I posted a question earlier about displaying factors of non-prime numbers and got this as a solution.

Below is a part of the code, but I have a little bit trouble understanding a few terms in them (since I am relatively new to ruby).

def factors(n)
   (1..n/2).select{|e| (n%e).zero?}.push(n)
 end

For instance,

  • What does the method select do in general?
  • What does .zero? do?

Then,

puts "#{n} is not a prime number =>#{factors(n).join(',')}"

What does .join(',') do?

It would be greatly appreciated if anyone can explain these terms to me in basic terms or simple concepts.

Vroryn
  • 125
  • 6

2 Answers2

1

select method filters a collection. You specify the condition (the predicate) in the block and select returns items who match that condition.

[1,2,3,4].select(&:even?)
 => [2, 4] 

i.zero? is another way to write i == 0

[0,2,3,0].select(&:zero?)
 => [0, 0] 

join method concatenate a collection as a string with the parameter as a separators between items

[0,2,3,0].select(&:zero?).join(' and ')
 => "0 and 0" 

Note

[1,2,3].select(&:even?) 

is a simpler way to write

[1,2,3].select { |item| item.even? }
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

i will try explain by following links and text from documentation

join()

Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses empty string.

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-")   #=> "a-b-c"

select

Returns a new array containing all elements of ary for which the given block returns a true value.

If no block is given, an Enumerator is returned instead.

[1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]

a = %w{ a b c d e f }
a.select { |v| v =~ /[aeiou]/ }  #=> ["a", "e"]

zero?

zero? → true or false
Returns true if num has a zero value.

Ruby html documentation: ruby-doc.org

Dmitry Cat
  • 475
  • 3
  • 11
  • 1
    Well, link-only answers are not useful. Either post as a comment, or elaborate, so that your answer still makes sense when/if links go dead. – Sergio Tulentsev Mar 03 '17 at 10:23