Skip to content

Instantly share code, notes, and snippets.

@efecarranza
Created January 19, 2015 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efecarranza/5803c16086ff9ea8b95e to your computer and use it in GitHub Desktop.
Save efecarranza/5803c16086ff9ea8b95e to your computer and use it in GitHub Desktop.
wyncode_methods.rb
# Author: piscu Carranza
# January 19, 2015
# Week Two - Wyncode
# Profile
# Problems With Floats
puts <<END
Using floats can be a pain. Therefore,
here is an idea on how to make sure no
random digits are added (stupid binary!).
END
total = 0
def addToTotal(item, total) # Takes two arguments to keep track of total
total += (item * 100)
total = total.to_i #to_i in order to drop decimal sign
return total
end
def backToDecimal(total)
return total / 100.0 # Divide by Float so that it won't chop the decimals
end
puts <<END
Having a Hash with Item => Value,
we can then use these functions to
keep track of our total without adding
random decimals. When we are ready to
check our balance at the end of the day,
we divide by 100 to go back to decimals.
END
# Tests with floats/integers.
total = addToTotal(33.50, total)
total = addToTotal(53, total)
puts backToDecimal(total)
puts
puts
# Christmas Tree
# Program to Print christmas tree by looping rather than typing
def print_tree(char)
num_star = 1
4.downto(1).each do |num_spaces| # Loop backwards to determine spaces needed
print(' ' * num_spaces)
puts (char * num_star)
num_star += 2
end
end
puts "Loop to create a christmas tree based on the character selected."
puts "Please select any character to display a tree."
response = gets.chomp
print_tree(response) # Tests with input from stupid/evil users.
# Using Join and Split
# I kept trying to split and then join, so that took about 50 tries
puts <<END
This statement shows how to convert [1,2,3]
to ["1", "2", "3"] by combining statements.
END
def split_join(*arr)
print arr.join(",").split(",")
end
# Tests: Will convert everything to one array, don't need it to be exactly an array.
split_join([1,2,3])
split_join([1, nil, 3])
split_join(["a", 3])
split_join("a", "b", "c")
split_join(1, 3, 5)
puts
puts
puts
puts <<END
split does not work on arrays, so I converted to_s
first, but that did not work. So I then tried join
first to see what would happen. Once I got a string
of the numbers, separated by commas, and read that
split would create an array, I knew i was on the
right track and it finally worked.
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment