Guest User

Untitled

a guest
Dec 10th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. =begin
  2. Suppose I have the following Array of tuples
  3.  
  4. [ ['a',1], ['b',2], ['c','3' ]
  5. How can I convert this to a Hash?
  6.  
  7. { 'a' => 1, 'b' => 2, 'c' => 3}
  8. Once I've written the algorithm, how would I make it generally available throughout my Ruby application?
  9.  
  10. =end
  11. def convert_to_hash(arr)
  12. final_arr = []
  13. arr.map{|el| final_arr << {el[0] => el[1]}}
  14. return final_arr
  15. end
  16.  
  17.  
  18. puts convert_to_hash([ ['a',1], ['b',2], ['c','3' ]]).inspect
  19.  
  20. #--------------------------------------------------------------------------------------------------------------
  21.  
  22. =begin
  23. Reverse a String in Ruby
  24. Write an iterative function to reverse a string.
  25. Do the same thing as a recursive function.
  26. =end
  27.  
  28. class String
  29. def reverse_me
  30. chars.to_a.inject([]){|arr, el| arr.unshift(el)}.join('')
  31. end
  32. end
  33.  
  34. puts "hello world".reverse_me
  35.  
  36.  
  37. =begin
  38. print multiplication table in Ruby
  39. =end
  40. x = (1..12)
  41. y = (1..12)
  42. y.each do |j|
  43. x.each {|i| print "%-3d" % (i*j)}
  44. print "\n"
  45. end
  46.  
  47. #--------------------------------------------------------------------------------------------------------------
  48. =begin
  49. print sum of numbers within given file
  50. =end
  51. puts File.open('file_with_integers').each_line.inject(0){|sum, line| sum + line.to_i}
  52.  
  53. #--------------------------------------------------------------------------------------------------------------
  54.  
  55. =begin
  56. Print odd numbers in Ruby
  57.  
  58. Write function to print the odd numbers from 1 to 99
  59. =end
  60.  
  61. puts [*1..99].collect{|el| el if el.odd?}.compact
  62.  
  63. #-------------------------------------------------------------------------------------------------------------
  64. =begin
  65. find next palindrome
  66. =end
  67.  
  68. def next_palindrome(n)
  69. n += 1
  70. n += 1 while n != n.to_s.reverse.to_i
  71. return n
  72. end
  73. puts next_palindrome(111)
Add Comment
Please, Sign In to add comment