Mike Mike - 11 months ago 46
Ruby Question

Ruby if else in array.each

New to Ruby here. I am attempting to put an if else statement in an array to send a string if a certain modulus == 0. for the life of me i can't find it anywhere. I am sure someone will find it ridiculously simple.

a = *(1..100)
a.each { |i| puts "three" if i % 3 == 0 elsif puts "five" if i % 5 == 0 else puts i}

Just not sure of the correct syntax. Still new to ruby and am trying to learn the syntax. Took a C class last semester and my brain keeps wanting to put in C syntax.

When I leave it as

a = *(1..100)
a.each { |i| puts "three" if i % 3 == 0}

it works fine, just trying to figure out how to add if else to it. Help is appreciated.

The answers below were really helpful. I am trying to take it a step further and call it into a function. It keeps returning 5, and not "five", or 3, and not "three".

here is my function:

def array_mod
a = *(1..100)
a.each { |i| if i % 3 == 0 && i % 5 == 0; i = "fifteen" elsif i % 3 == 0; i = "three" elsif i % 5 == 0; i = "five" else i = i end }


and here is my attempt at calling it.

require "minitest/autorun"
require_relative "array_modulus.rb"

class TestArrayFunction < Minitest::Test

def test_array1

results = array_mod

assert_equal(100, results.length)

def test_array2

results = array_mod
assert_equal("three", results[2])


I was told it is not updating my array. Thanks again.

Answer Source

Please see if the below code helps

def abc
   a = *(1..100)
   a.each do |i|
       if i % 3 == 0 
       puts "three"
       elsif i % 5 == 0
       puts "five"
         puts i

=> :abc

2.3.0 :013 > abc

this gives the desired output in irb mode.