-2

I'm having array where values could be only 1 or 0.

array_example = [0, 0, 0, 0, 1]

As you can see there is already 1 in the array, so i need to forbid the case when there could be 2 or more elements with value 1.

Just as example, in array should be only 1 element with value 1, so if array will be like this, i should get an error.

array_example = [1, 0, 0, 0, 1]

Ruby 1.8.7

Rails 2.3.4

Viktor
  • 323
  • 4
  • 15
  • https://ruby-doc.org/stdlib-1.8.7/libdoc/set/rdoc/Set.html – anothermh Mar 17 '20 at 23:35
  • Set is collecting and ignoring duplicates, but i need to check value `1` on duplicates only. – Viktor Mar 17 '20 at 23:38
  • `array_example.select{ |element| element == 1 }.size > 1` or do I not understand your question? – Archer Mar 17 '20 at 23:48
  • `array_example << 1 unless array_example.include?(1)` More at https://stackoverflow.com/q/1986386/3784008. – anothermh Mar 17 '20 at 23:49
  • Do you want `[123] << 4` to operate normally but `[1,2,3] << 2` to raise an exception? – Cary Swoveland Mar 18 '20 at 03:22
  • I'd strongly recommend updating your Ruby. 1.8.7 is extremely out of date. – the Tin Man Mar 18 '20 at 06:15
  • Since you're using Rails: `array_example.many? { |n| n == 1 }` returns `true` if there's more than one `1` in the array. – Stefan Mar 18 '20 at 08:38
  • @Stefan I think `array_example.count(1) > 1` probably wins the prize for succinctness, since it doesn't require a block. – BobRodes Mar 18 '20 at 08:50
  • @CarySwoveland OP says values can only be `1` or `0`? – BobRodes Mar 18 '20 at 08:51
  • 1
    @BobRodes it's shorter, but `count` always traverses the whole array whereas `many?` stops as soon as it finds a second match. – Stefan Mar 18 '20 at 09:02
  • @Stefan Good to know, Thanks! I know Ruby quite well, and Rails not at all at present, and thinking about how to get the same functionality in straight Ruby I can see where a method like `many?` would be useful. – BobRodes Mar 18 '20 at 19:45

1 Answers1

2

Although your explanation could use more clarity, I believe you are saying that you have an array of any number of zeros and zero or one 1. And, if a 1 gets added to an array already containing one, to raise an error.

If I understand what you're trying to do correctly, it isn't difficult. All you have to do is select all the elements that equal 1 and raise an error if the size of the result is greater than 1:

raise 'Too many ones' if array_example.select { |e| 1 == e }.size > 1

This will raise the default RuntimeError. Of course, you can raise any sort of custom error that you like (and you probably should create a custom one for this if you're going to handle it using rescue).

Edit: Cary's suggestion of Array#count is indeed more direct. So:

raise 'Too many ones' if array_example.count(1) > 1
BobRodes
  • 5,990
  • 2
  • 24
  • 26