Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =begin
- Suppose I have the following Array of tuples
- [ ['a',1], ['b',2], ['c','3' ]
- How can I convert this to a Hash?
- { 'a' => 1, 'b' => 2, 'c' => 3}
- Once I've written the algorithm, how would I make it generally available throughout my Ruby application?
- =end
- def convert_to_hash(arr)
- final_arr = []
- arr.map{|el| final_arr << {el[0] => el[1]}}
- return final_arr
- end
- puts convert_to_hash([ ['a',1], ['b',2], ['c','3' ]]).inspect
- #--------------------------------------------------------------------------------------------------------------
- =begin
- Reverse a String in Ruby
- Write an iterative function to reverse a string.
- Do the same thing as a recursive function.
- =end
- class String
- def reverse_me
- chars.to_a.inject([]){|arr, el| arr.unshift(el)}.join('')
- end
- end
- puts "hello world".reverse_me
- =begin
- print multiplication table in Ruby
- =end
- x = (1..12)
- y = (1..12)
- y.each do |j|
- x.each {|i| print "%-3d" % (i*j)}
- print "\n"
- end
- #--------------------------------------------------------------------------------------------------------------
- =begin
- print sum of numbers within given file
- =end
- puts File.open('file_with_integers').each_line.inject(0){|sum, line| sum + line.to_i}
- #--------------------------------------------------------------------------------------------------------------
- =begin
- Print odd numbers in Ruby
- Write function to print the odd numbers from 1 to 99
- =end
- puts [*1..99].collect{|el| el if el.odd?}.compact
- #-------------------------------------------------------------------------------------------------------------
- =begin
- find next palindrome
- =end
- def next_palindrome(n)
- n += 1
- n += 1 while n != n.to_s.reverse.to_i
- return n
- end
- puts next_palindrome(111)
Add Comment
Please, Sign In to add comment