Skip to content

Instantly share code, notes, and snippets.

@hauntedhost
Created October 8, 2017 16:27
Show Gist options
  • Save hauntedhost/86e75c1b6af6484709e5f0cdf6aeafbf to your computer and use it in GitHub Desktop.
Save hauntedhost/86e75c1b6af6484709e5f0cdf6aeafbf to your computer and use it in GitHub Desktop.
ruby-exercises-02.md

hello

Write a method hello that takes one argument and calls puts so that the output if called with, e.g., hello("Alli") would be Hello there Alli!

Player

Write a class Player that can be initialized with one argument name and returns a player instance with the keys name, health and role.

  • The name key should be assigned the given name argument.
  • The health key should be a random integer from 50 to 100.
  • The role key should be a random role from an array of role names.

You can use this array of role names (or make up your own):

role_names = [
  "Barbarian",
  "Bard",
  "Cleric",
  "Druid",
  "Fighter",
  "Monk",
  "Paladin",
  "Ranger",
  "Rogue",
  "Sorcerer",
  "Wizard",
]

Example use of using Player class:

player = new Player("Puppy Tummies")
=> #<Player:0x007fe27657c488 @health=52, @name="Puppy Tummies", @role="Rogue">

sum

Write a method sum that sums all the numbers in an array of numbers. Given an empty array it should return 0.

Examples:

sum([1, 2, 3, 4])
=> 10

squares

Write a method squares that takes an array of numbers and returns an array of numbers where each number is squared. For example squares([2, 3, 4]) should return [4, 9, 16]. (Given an empty array should return []).

multiply

Write a method multiply that takes an array of numbers, multiples all of them and returns the resulting number. For example, multiply([2, 3, 4]) should return 24.

find_longest_word

Write a method find_longest_word that takes an array of words and returns the longest one. For example, find_longest_word(['onion', 'cucumber', 'garlic']) should return 'cucumber'.

Hint: Remember that you can use the .length method of a string, e.g. "hello".length.

char_count

Write a method char_count that takes a string and returns frequency counts of the characters contained in it. Return the frequency counts as a hash with letter keys and integer values. For example, char_count("hello") should return {h: 1, e: 1, l: 2, o: 1}.

Hint: You can split a string into an array of letters using string.split(''). For example "hello".split('') returns the array ['h', 'e', 'l', 'l', 'o'].

This is a challenging problem. Please ask questions if you get stuck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment