Gregorio Pompei
Gregorio Pompei

Reputation: 69

How to set a variable to an if condition

I have this condition:

arr1 = [1, 2, 3, 4]

arr1.each do |num|
  if num == arr1.last
    print "#{num}\n"
    exit
  else
    print "#{num} x "
  end
end

and I have to print this like a variable, maybe called num_printer, so that if I write

  puts num_printer

it should print this

  1 x 2 x 3 x 4

But I don't know how to do this. Can anyone help me?

Upvotes: 0

Views: 51

Answers (2)

Jordan Running
Jordan Running

Reputation: 106027

There are simpler ways to accomplish this as Maxim points out in their answer, but to answer your question, you could accomplish this by initializing an empty string variable and then in your each block appending text to the variable instead of printing it:

arr1 = [1, 2, 3, 4]
nums_str = ""

arr1.each do |num|
  if num == arr1.last
    nums_str << num.to_s
  else
    nums_str << "#{num} x "
  end
end

puts nums_str
# => 1 x 2 x 3 x 4

See it on repl.it: https://repl.it/@jrunning/ArcticDeficientArchitecture

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

Basically, you want to insert something (' x ' in your case) between the elements and output the result. Use join

puts arr1.join(' x ')

Upvotes: 0

Related Questions