-1

I need to randomly pick a name from an array in Ruby and then check if it uppercase. So far I have:

def namegenerator
  return @name.sample
end

def namechecker
  if name.upcase then
    check = TRUE
  else
    check = FALSE
  end
end

It needs to be as two separate methods like this.

Viktor
  • 2,623
  • 3
  • 19
  • 28
Pengoo
  • 13
  • 1
    Possible duplicate of [How can I check a word is already all uppercase in Ruby?](https://stackoverflow.com/questions/8529595/how-can-i-check-a-word-is-already-all-uppercase-in-ruby) – Viktor Oct 26 '19 at 13:58
  • Try this: `arr.sample.then { |word| word == word.upcase }`. See [Object#then](https://ruby-doc.org/core-2.6.3/Object.html#method-i-then) (aka `yield_self`). – Cary Swoveland Oct 26 '19 at 14:25
  • Welcome to SO! Your code example doesn't show a genuine attempt to solve the problem, it's only an outline of the code. Please see "[ask]" and the linked pages and "[mcve](https://stackoverflow.com/help/minimal-reproducible-example). – the Tin Man Oct 27 '19 at 00:19

3 Answers3

3

Something like this:

def sample_word(words)
  words.sample
end

def upcase?(word)
  word == word.upcase
end

And then something like:

words = %w[APPLE banana CherRy GRAPE]

word = sample_word(words)
puts word # e.g. BANANA
puts upcase?(word) # will print true
mechnicov
  • 12,025
  • 4
  • 33
  • 56
0

Maybe something like this:

class NameGenerator
    def initialize(size, items)
        @name = ""
        @size = size
        @items = items
    end

    def namegenerator
        @name = @items.sample(@size).to_s
    end

    def namechecker?
        @name == @name.upcase
    end

    def name 
        @name
    end
end

ng = NameGenerator.new 1, ["name", "Name", "NAME"]
ng.namegenerator

puts ng.name, ng.namechecker?

Update

I've posted code without much thinking about abstraction and i think it would be much better to encapsulate name and upper case check to separate class and make it immutable, then make generator class that selects one entity from collection.

class NameGenerator
    def initialize(items)
        @items = items
    end

    def next
        @items.sample
    end
end

class Name 
    attr_reader :name

    def initialize(name)
        @name = name
    end  

    def is_uppercase?
        @name.match(/\p{Lower}/) == nil
    end
end 

ng = NameGenerator.new [
    Name.new("name"),
    Name.new("Name"),
    Name.new("NAME"),
    Name.new("na-me")
]

name = ng.next
puts name.name, name.is_uppercase?
Edin Omeragic
  • 1,948
  • 1
  • 23
  • 26
0

If you just want to check just the first letter:

names = %w(Kirk mccoy scott Spock)

names.sample.then { |name| [name, name[0] == name[0].upcase] }
#=> ["mccoy", false]
iGian
  • 11,023
  • 3
  • 21
  • 36