Skip to content

Instantly share code, notes, and snippets.

@owade
Last active September 25, 2015 08:22
Show Gist options
  • Save owade/8f3653847d9c3d555ae2 to your computer and use it in GitHub Desktop.
Save owade/8f3653847d9c3d555ae2 to your computer and use it in GitHub Desktop.
SOME RUBY CODE CHALLENGES I HAVE BEEN DOING
class Age
attr_reader :age
def initialize(firstName, lastName, age)
@firstName = firstName
@lastName = lastName
@age = age
end
def full_name
"#{@firstName} #{@lastName}"
end
#def age
# "#{@age}"
# #p @age
#end
end
a=Age.new("felix","omosh",45)
p a.full_name
p a.age
p '--------------------------------------------------------'
person = Age.new('Yukihiro', 'Matsumoto', 47)
puts person.full_name
puts person.age
class Array
def square
self.map do |i|
i*i
end
end
def cube
self.map do |i|
i*i*i
end
end
def sum
self.inject{|sum,x| sum + x }
end
def even
self.select { |a| a %2==0 }
end
def odd
self.select { |a| a %2!=0 }
end
def average
self.inject{ |sum, el| sum + el }.to_f / self.size
end
end
numbers = [1, 2, 3.5395, 4.134, 5]
p numbers.average
class Array
def contains_all?(other_array)
p (other_array - self).empty?
end
end
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
items.contains_all?([1, 2, 3]) # should == true
items.contains_all?([1, 5, 13]) # should == false because 13 is not within the items array
class Array
def even
p ints.select &:even?
end
def odd
ints.select &:odd?
end
def under(x)
ints.select { |elem| elem < x }
end
def over(x)
ints.select { |elem| elem > x }
end
def in_range(r)
ints.select { |x| r.include?(x) }
end
def ints
select { |x| x.is_a? Fixnum }
end
end
##############################################################################
#def filter(arr)
#
#p arr.select{|x| x.even?} #even
#p arr.reject{|x| x.even?} #odd
#p arr.select{|x| x < 4} #under <4>
#p arr.select{|x| x > 4} #over <4>
#p arr[1..3] #in-range <1..3>
#end
[1,2,3,4,5].even
#p (1..3).to_a.each{|l| l}
#even # [1,2,3,4,5].even should return [2,4]
#odd # [1,2,3,4,5].odd should return [1,3,5]
#under # [1,2,3,4,5].under(4) should return [1,2,3]
#over # [1,2,3,4,5].over(4) should return [5]
#in_range # [1,2,3,4,5].in_range(1..3) should return [1,2,3]
p "this is me".capitalize
p "this is me".capitalize.split.map(&:capitalize).join(' ')
#state_capitals = [{state: 'Maine', capital: 'Augusta'}]
#capital(state_capitals)[0] # returns "The capital of Maine is Augusta"
#
#country_capitals = [{'country' => 'Spain', 'capital' => 'Madrid'}]
#capital(country_capitals)[0] # returns "The capital of Spain is Madrid"
#
#mixed_capitals: [{"state" => 'Maine', capital: 'Augusta'}, {country: 'Spain', "capital" => "Madrid"}]
#capital(mixed_capitals)[0] # returns "The capital of Maine is Augusta"
#FIND THE CAPITALS
#def capital(capitals_hash_array)
# "The capital of #{} is #{}"
#end
def access_cap(arr_hash)
#x=arr_hash[0]["country"]==nil ? "state":"country"
if arr_hash[0]["country"]==nil || arr_hash[0][:country]==nil
x="state" || x="state".to_s.to_sym if arr_hash[0]["country"]==nil
else
x="country" || x="country".to_sym if arr_hash[0]["state"]==nil
end
p "The capital of #{arr_hash[0][x.to_sym]} is #{arr_hash[0]["capital".to_sym]}"
p x
end
access_cap([{'country' => 'Spain', 'capital' => 'Madrid'}])
class Ghost
attr_accessor :color
def initialize()
colorList = ['white', 'yellow', 'purple', 'red']
prng = Random.new
#self.color=colorList[prng.rand(0..3) ]
# self.color=colorList.shuffle.sample
self.color=colorList.shuffle.sample(random: Random.new(1))
#self.color=colorList.sample(1)
end
end
k=Ghost.new
b=Ghost.new
c=Ghost.new
d=Ghost.new
p k.color
p b.color
p c.color
p d.color
def greet(name)
p 'Hello'+ ' ' +name.capitalize+'!'
end
greet('felix')
#def power_of_4(number)
#
# if number.kind_of?Integer
# if(Math.log(number,4) % 1 == 0 if number >0)
# true
# elsif !number.is_a? Integer
# false
# else
# false
# end
# else
# false
# end
#
#
#end
#prefered soln
def power_of_4(n)
n.is_a?(Integer) && n>0 ? Math.log(n, 4) % 1 == 0 : false
end
p power_of_4(-4)
def power_of_two?(x)
p Math.log(x,2)%1==0
end
power_of_two?(128)
class Person
attr_accessor :myName
def initialize(a)
@myName=a
end
def greet(name2)
"Hello #{name2}, my name is #{@myName}"
end
end
c=Person.new('felix')
p c.greet('jane')
p c.myName
#----------------------------------------------------------ANSWER----------------------------------------------------------------
#class Person
# attr_reader :name
# def initialize(name)
# @name = name
# end
#
# def greet(yourName)
# "Hello #{yourName}, my name is #{@name}"
# end
#end
def one_through_x(num)
# Your code here
1.upto(num) do |f|
p f
end
end
one_through_x(10)
def remove_url_anchor(url)
p url.split('#').first
end
# returns 'www.codewars.com'
remove_url_anchor('www.codewars.com#about')
# returns 'www.codewars.com?page=1'
remove_url_anchor('www.codewars.com?page=1')
#------------------Reverse without using array,reverse---------------------------------------------------------------------------------
arr4=[1,2,3,4,5,6]
def reverse(arr)
temparr = []
for x in 0..(arr.length-1) # or: arr.length.times
temparr.push(arr.pop)
end
arr = temparr
p arr
end
reverse(arr4)
#------------------method2---------------------------------------------------------------------------------
arr = [1,2,3,4,5] # given an arbitrary array
final_idx = arr.length-1
for x in 0..(arr.length/2)
temp = arr[x]
arr[x] = arr[final_idx - x]
arr[final_idx - x] = temp
end
#----------------------method3----------------------------------------------------------------------------------
arr = [1,2,3,4,5] # given an arbitrary array
final_idx = arr.length-1
for x in 0..(arr.length/2)
arr[x], arr[final_idx - x] = arr[final_idx - x], arr[x]
end
#----------------------------------------------------------------------------------------------------------------
def solution(value)
sprintf('%.2f', value)
end
p solution(45.329)
def solution(sentance)
p sentance.split.reverse.join(' ')
end
solution("The greatest victory is that which requires no battle")
#def camelize(str)
# #k=str.gsub /\W/, ' '
# k=str.tr('^A-Za-z0-9', ' ')
# #str.split(' ').collect(&:capitalize).join
# k.split(' ').collect(&:capitalize).join
#end
def camelize(str)
str.split(/\W|_/).map(&:capitalize).join
end
p camelize("example name") # => ExampleName
p camelize("your-NaMe-here") # => YourNameHere
p camelize("testing ABC") # => TestingAbc
p camelize("t?///es^^t&&i**ng ABC")
p camelize("john doe")
value = "carrot,squash,corn,broccoli,spinach"
l=value.split(",", 3)
p l
#Given an array of numbers return an array of numbers from the array that qualify as perfect squares.
# A perfect square is defined as a whole number that, when square rooted, is a whole number.
#(Such as 1, 4, 9, 16, etc, etc.)Given an array of numbers return an array of numbers from the array that qualify as perfect squares.
#A perfect square is defined as a whole number that, when square rooted, is a whole number. (Such as 1, 4, 9, 16, etc, etc.)
#get_squares(1..16) # => [1, 4, 9, 16]
#get_squares(1..100) # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
=begin
Test.assert_equals(get_squares((1..16)), [1,4,9,16])
Test.assert_equals(get_squares((1..100)), [1,4,9,16,25,36,49,64,81,100])
Test.assert_equals(get_squares([4,1,16,1,10,35,22]), [1,4,16])
=end
def get_squares(array)
array.to_a.each { |a| p a if Math.sqrt(a)%1==0}
# Math.sqrt(9)
end
get_squares([4,16,89,100])
p '-------------------------------------------------------------------'
get_squares((1..16))
p '-------------------------------------------------------------------'
get_squares([100,60,49,16])
#p (1..16).to_a
# 1.upto(100).each { |a| print a," " }
def sumDigits(number)
ary=number.to_s.chars.map(&:to_i) #create an array of digits from a number
#sumo=0
#ary.each do |f|
# p sumo+=f
#end
p ary.inject{|sum,x| sum + x.abs } #add the absolute values of the digits in the array
end
sumDigits(-32)
class Person2
def initialize(name)
@name = name
end
def greet(other_name)
p "Hi #{other_name}, my name is #{@name}"
end
end
p=Person2.new('felix')
p.greet('owade')
def unique(arr1)
#p arr1.uniq
p arr1 & arr1
end
unique([1,3,2,6,8,4,7,8])
unique([])
unique([5, 2, 1, 3])
unique([1, 5, 2, 0, 2, -3, 1, 10])
#Write a method sum that accepts an unlimited number of integer arguments, and adds all of them together.
#The method should reject any arguments that are not integers, and sum the remaining integers.
#sum(1,2,3)
## => 6
#def sum(arr)
# arr.to_a if arr.each{|a| a.integer?==true}
# b=0
# arr.each{|a| b+=a}
# p arr
#end
def is_number?(obj)
p obj.to_s==obj.to_i.to_s
end
def sum2(n,p,*others)
r=others.select{|a| a.is_a?Integer}
k = r.reduce(:+)
p n+p+k
end
sum2(1,2,3,9)
is_number?('424js')
is_number?('42464')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment