0

Is there anyway to call multiple end statement

Like I have a for loop and an if-else statement so can I do two ends together like end[2] or end*2

My statement is: a.each do |i| if i<0 then l+=1 elsif i>0 then s+=1 else h+=1 end end Here you can see there are two end statements can I turn them into one and shorten the code.

Thanks in Advance :)

  • 2
    No, there isn't – max pleaner Feb 24 '21 at 07:58
  • Why do you need such a one-liner? You can use curly braces with `each` like this `a.each { |i| here_your_code }`. – Yakov Feb 24 '21 at 08:00
  • I wanted to solve the problem is shortest code – Saad Yar Khan Feb 24 '21 at 08:21
  • Your question is unclear. What is an "end statement"? There is no such thing as an "end statement" in Ruby. In fact, there are no statements *at all* in Ruby. And what does it mean to "call" an end statement? You cannot call statements in Ruby. Actually, you cannot really call anything in Ruby, you can only send a message, and Ruby will call a method for you. – Jörg W Mittag Feb 24 '21 at 08:35
  • Sir may I know what is it called then, Because I am very new to ruby – Saad Yar Khan Feb 24 '21 at 09:38

1 Answers1

0

can I do two ends together like end[2] or end*2

No, there isn't such syntax.

But you could rewrite your code in other ways, e.g. via <=> and tally:

a = [-2, -1, 0, 1, 2, 3]

counts = a.map { |i| i <=> 0 }.tally

l, s, h = counts.values_at(-1, 0, 1)

l #=> 2
s #=> 3
h #=> 1
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • Thx What does the count.values and .tally do – Saad Yar Khan Feb 24 '21 at 08:22
  • @SaadYarKhan have a look at the docs. `tally` returns the number of occurrences as a hash and `values_at` fetches the values for `-1`, `0`, and `1` which correspond to negative, zero and positive numbers. – Stefan Feb 24 '21 at 08:43