Skip to content

Instantly share code, notes, and snippets.

@amaxwellblair
Last active December 2, 2015 00:16
Show Gist options
  • Save amaxwellblair/8f32e6dbda226157b765 to your computer and use it in GitHub Desktop.
Save amaxwellblair/8f32e6dbda226157b765 to your computer and use it in GitHub Desktop.

String and Integer Riddles

Strings

How can I tell how many characters are in a string? Do spaces count?

.length, yes

How can I capitalize the first character of a string? What happens if it is a number?

.capitalize, nothing

How can I turn a string backwards?

.reverse

How can I tell if two words have the same number of characters?

str1.length == str2.length

How can I tell if a word has all capital letters? upcase?(str) i = 0; str.each_char do |x| x.downcase != str[i] ? nil : return false i += 1 end return true end

How can I tell if a word has all lower case letters?

downcase?(str) i = 0; str.each_char do |x| x.upcase != str[i] ? nil : return false i += 1 end return true end

How can I tell if a word is a palindrome? (The word is the same forwards and backwards.)

str == str.reverse

How can I tell if a sentence is the same forwards and backwards?

str == str.split(" ").reverse.join(" ")

How can I replace an occurrence of a single character in a string with another character?

str[str.index(char_change)] = new_char

How can I replace ALL occurrences of a single character in a string with another character?

str.each_char do |c| c == char_change ? c = new_char : nil end

How do I insert 5 asterisks at the start of a string? What about at the end of a string? What about x asterisks?

What if I wanted to have a string that's four characters long, but I want to make a big string thats 14 characters in length, with the original string in the middle, with asterisks on either side of the original string to make it reach the desired length?

What if I wanted to replace the padding character with spaces? And a variable total length?

What are two ways in which you can determine if an integer is odd? (Or even.)

How can I convert a string into a number?

How can you tell if a number is a palindrome? (303, 1221, 123321)

How can you tell if a number is divisible by 3? By 9? By x?

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