Skip to content

Instantly share code, notes, and snippets.

@ssnravi
ssnravi / gist:9063535
Created February 18, 2014 02:28
Prime no in a given range using "Def"
first_num = 2
last_num = 20
def prime? num
return false if num <=1
2.upto(num/2).each { |y| return false if num % y == 0}
true
end
first_num.upto(last_num) do |temp|
@ssnravi
ssnravi / gist:9057086
Created February 17, 2014 19:17
Strings sort by length
arr = ["apple", "bananna", "pineapple", "orange"]
puts arr.sort_by {|x| x.length}
@ssnravi
ssnravi / gist:9056938
Created February 17, 2014 19:09
Count #chars in a string
s = "I am Ravi Suraneni"
def count_word_characters(s)
h = Hash.new(0)
s.downcase.each_char do |char|
next unless char =~/\w/
h[char] += 1
end
h
student = {"First Name:" => "John",
"Last Nmae:" => "Doe",
"Subjects:" => "Physics, Chemistry, Maths",
"Marks:" => "Physics: 75, Maths: 85, Chemistry: 98"
}
student.each {|key, value| puts key, student[key]}
@ssnravi
ssnravi / gist:8995612
Created February 14, 2014 04:08
Sum of first N prime numbers
num = 1000
def prime? num
return false if num <=1
2.upto(num/2).each { |y| return false if num % y == 0}
true
end
temp = 1
@ssnravi
ssnravi / gist:8983366
Created February 13, 2014 20:39
Pallindrome
print "Enter your string: "
string = gets.chomp
if string == string.reverse
puts "#{string} is a pallindrome"
else
puts "#{string} is not a pallindrome"
end
@ssnravi
ssnravi / gist:8967054
Last active August 29, 2015 13:56
Factoroal
#Factorial: n! = n*(n-1)*(n-2)*...1
print "Enter a number: "
num = gets.chomp.to_i
fact = 1
puts "Factorial for #{num} is: "
num.downto(1) {|x| fact *= x}
puts fact
@ssnravi
ssnravi / gist:8950837
Last active August 29, 2015 13:56
GCD
print "Enter first number here: "
first_num = gets.chomp.to_i
print "Enter second number here: "
second_num = gets.chomp.to_i
puts "GCD of #{first_num} and #{second_num} is: "
temp=1
@ssnravi
ssnravi / gist:8948662
Last active August 29, 2015 13:56
Prime number
print "Enter a number here: "
num = gets.chomp.to_i
prime = true
2.upto(math.sqrt(num)).each do |x|
if num % x == 0
not_prime = false
break
end
@ssnravi
ssnravi / gist:8946792
Created February 11, 2014 23:44
Integer methods
x=10
x.downto(1) {|n| print n, " "}
x=8
y=12
puts x.gcd(y)
x=8
puts x.next