Rubyn00b
Rubyn00b

Reputation: 23

Really new to RUBY and would appreciate some guidance

I'm trying to def random_both in order to call both a random_case and a random_name and I think I'm just messing up the syntax to call it right, I'm super new to Ruby and am just really frustrated by this as it feels like it should be simple.

def upper(string)
  string.upcase
end

def lower(string)
 string.downcase
end

def random_name
 ["Ollie", "Ana"].sample
end

def random_case(string)
 [upper(string), lower(string)].sample
end

**def random_both
  return random_name
  return random_case
end**

puts "My name is #{random_both()}"

Upvotes: 2

Views: 53

Answers (3)

Ritesh Choudhary
Ritesh Choudhary

Reputation: 782

You can run this using below simple code

def random_name
  ['Ollie', 'Ana'].sample 
end

def random_case(string)
  [string.upcase, string.downcase].sample
end

def random_both 
  random_case(random_name) 
end

10.times{ puts "My name is #{random_both}"  }

output

My name is ANA
My name is OLLIE
My name is ANA
My name is ana
My name is ana
My name is ollie
My name is OLLIE
My name is ana
My name is ollie
My name is ollie

if you want to see advanced use of ruby you can do like below

def random_both 
  %w[Ollie Ana].sample
               .send(%i[upcase downcase].sample)
               .prepend('My name is ')
end

10.times{ puts random_both }

output

My name is ollie
My name is ANA
My name is OLLIE
My name is ollie
My name is ANA
My name is ANA
My name is OLLIE
My name is ollie
My name is ollie
My name is ANA

Upvotes: 0

Cassandra S.
Cassandra S.

Reputation: 770

You can only return once from a function, so your random_both will return random_name, and then it's done. You're also calling random_case without an argument in random_both.

Consider building your string before you return it, something like this, perhaps:

def random_both
  name = random_name
  name_cased = random_case(name)
  "#{name} #{name_cased}"
end

In ruby, parens () are optional, and the return is implicit, so you don't need to use them explicitly.

Here is an explanation on how functions work.

Upvotes: 0

Stefan
Stefan

Reputation: 114158

You probably want:

def random_both
  random_case(random_name)
end

It calls random_name and passes that value (i.e. either "Ollie" or "Ana") to random_case which turns it into its uppercase or lowercase variant:

random_both #=> "OLLIE"
random_both #=> "ollie"
random_both #=> "ANA"
random_both #=> "OLLIE"
random_both #=> "ana"

Upvotes: 2

Related Questions