How do I return a "non value" or "empty" value?

ruby

#1

I'm curious to see if anybody knows of any way to produce a non value from a method, function, etc.

I did a fair amount of googling and could not find a good answer to this. Now, of course there are a few ways to express "nothing" in Ruby, including the likes of "nil", "[]" and "". But these are not truly "nothing".

The reason why I bring this up is because sometimes I have a problem that involves having an array that spits out its selection or collection of indices and one of them happens to be "nil", "", or [], when I actually intended that index to not exist at all. While there are ways to use the "break" or "next" commands to skip a loop in the method to perhaps avoid this, I believe I may be doing it wrong. Are there any other ways to accomplish this? Here are some situations that I have been running into problems with:


Example code:

def ordered_vowel_words(str)  # method that presents a string that contains words which have their vowels in alphabetical order
    words = str.split(" ")
    ordered = []
    
    words.each do |word|
      ordered << ordered_vowel_word?(word)
    end
         
    ordered = ordered.join(" ")
    puts ordered
    return ordered
end

def ordered_vowel_word?(word)  # method that presents the word if its vowels are in alphabetical order
    vowels = []
    word.each_char do |char|
    if char == "a" || char == "e" || char == "i" || char == "o" || char == "u"
        if (vowels.empty? == false) && (char < vowels.last)
            word = nil
            return
        end
        vowels << char
    end
    end
    puts word
    return word
end

ordered_vowel_words("this is a test of the vowel ordering system") # == this is a test of the vowel "" system

# the result should be 'this is a test of the vowel system'

#2

Also, I understand the code above may be hard to read. I have seen users on this forum display their code in nice shaded code text boxes. How can I do this to make it easier to read the code?


#3

```

Your code here

```

#4

In response to my own example code, I found a fix that will allow me to get the solution I need. It involves returning "false" with the second 'helper' method if word does not contain vowels in alph. order, and returning true otherwise.

Then in the first method, I can choose to .push each of the words if they evaluate to true(meaning that the falsest will just fall by the wayside, close enough to being "nothing").

This boolean way of handling it is the only solution I have found. Is there something else that I could use instead?


#5

I suppose another way of expressing what I'm looking for is a way to "take no action" or "omit". So if I reach a point in my method where I just want the entire method to put on its brakes and STOP what its doing, or take no further action... can I?