Last active
May 6, 2019 01:47
-
-
Save duqcyxwd/5557970 to your computer and use it in GitHub Desktop.
Ruby pratice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Car | |
def self.newFerrari | |
car = Car.new | |
car.name = "FF" | |
car.top_speed = 208 | |
car | |
end | |
def self.newTesla | |
car = Car.new | |
car.name = "Model S" | |
car.top_speed = 125 | |
car | |
end | |
# ... (instance methods & instance variables) | |
end | |
car = Car.newFerrari | |
car.top_speed #=> 208 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
p xs = %w[a b c] # ['a','b','c'] | |
puts "" | |
ys = xs.each {|x| x.capitalize } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map {|x| x.capitalize } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map! {|x| x.capitalize } | |
p xs | |
p ys | |
puts "" | |
puts "Second try" | |
xs = %w[a b c] # ['a','b','c'] | |
ys = xs.each {|x| x.capitalize! } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map {|x| x.capitalize! } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map! {|x| x.capitalize! } | |
p xs | |
p ys | |
puts "" | |
puts "Third try" | |
xs = %w[a b c] # ['a','b','c'] | |
ys = xs.each {|x| x = x.capitalize } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map {|x| x = x.capitalize } | |
p xs | |
p ys | |
puts "" | |
ys = xs.map! {|x| x = x.capitalize } | |
p xs | |
p ys | |
puts "" | |
arr = [1,2,3] | |
arr2 = arr.each{|element| element = element * 2} | |
#arr与arr2仍然都等于[1,2,3] each返回原数组 遍历内对元素的更改不会保存 | |
p "arr is #{arr}" | |
p "arr2 is #{arr2}" | |
puts "" | |
arr2 = arr.map{|element| element = element* 2} | |
#arr等于[1,2,3] arr2等于[2,4,6] map返回更改后的数组 遍历内对元素的更改不会保存 | |
p "arr is #{arr}" | |
p "arr2 is #{arr2}" | |
puts "" | |
arr2 = arr.map!{|element| element = element * 2} | |
#arr与arr2都等于[2,4,6] map!返回更改后的数组 遍历对元素内的更改会保存 | |
p "arr is #{arr}" | |
p "arr2 is #{arr2}" | |
puts "" | |
=begin | |
["a", "b", "c"] | |
["a", "b", "c"] | |
["a", "b", "c"] | |
["a", "b", "c"] | |
["A", "B", "C"] | |
["A", "B", "C"] | |
["A", "B", "C"] | |
Second try | |
["A", "B", "C"] | |
["A", "B", "C"] | |
["A", "B", "C"] | |
[nil, nil, nil] | |
[nil, nil, nil] | |
[nil, nil, nil] | |
Third try | |
["a", "b", "c"] | |
["a", "b", "c"] | |
["a", "b", "c"] | |
["A", "B", "C"] | |
["A", "B", "C"] | |
["A", "B", "C"] | |
"arr is [1, 2, 3]" | |
"arr2 is [1, 2, 3]" | |
"arr is [1, 2, 3]" | |
"arr2 is [2, 4, 6]" | |
"arr is [2, 4, 6]" | |
"arr2 is [2, 4, 6]" | |
=end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fixnum | |
def plus_one | |
self + 1 | |
end | |
end | |
5.plus_one #=> 6 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User | |
attr_accessor :name, :email, :bio, :age, :sex | |
def initialize(hash = {}) | |
# hash = {} make sure it take empty parameter | |
@name = hash[:name] || "n/a" | |
@email = hash[:email] || "n/a" | |
@bio = hash[:bio] || "n/a" | |
@age = hash[:age] || "n/a" | |
@sex = hash[:sex] || "n/a" | |
end | |
end | |
#This is note for hash in ruby |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hello | |
"Hello world" | |
end | |
puts hello | |
def hello2 | |
a = 1 | |
b = 2 | |
a + b | |
end | |
puts hello2 | |
puts link("http://google.com", "Google") | |
Nil | |
puts "Bloc"[7] | |
puts "Bloc"[2] | |
puts "Bloc"[1] | |
nilly = nil | |
puts nilly | |
Method | |
# p = principal amount | |
# r = annual rate of interest | |
# t = number of years | |
# n = number of times it is compounded | |
def compound_interest(name, p, r, t, n) | |
a = p * (1 + r/n) ** (n*t) | |
"After #{n} years #{name} will have #{a} dollars!" | |
end | |
puts compound_interest("Bob", 100, 0.05, 40, 12) | |
puts compound_interest("Joe", 250, 0.06, 50, 12) | |
Specs | |
require "./app.rb" | |
describe "link_to" do | |
it "should return a valid link for Bloc" do | |
link_to("Bloc", "http://www.bloc.io").should eq("<a href='http://www.bloc.io'>Bloc</a>") | |
end | |
it "should return a valid link for Google" do | |
link_to("Google", "http://www.google.com").should eq("<a href='http://www.google.com'>Google</a>") | |
end | |
end | |
def link_to(link_name, link_address) | |
"<a href='#{link_address}'>#{link_name}</a>" | |
end | |
require 'date' | |
def next_birthday(birthday) | |
next_year = birthday.next_year | |
next_year.strftime("%D") | |
end | |
next_birthday(Date.new(2013,6,1)) | |
#about method strftime: http://ruby-doc.org/stdlib-2.0/libdoc/date/rdoc/Date.html#method-i-strftime | |
Specs | |
require "./app" | |
describe "hello" do | |
it "should return 'Hello World' when passed 'World'" do | |
hello("World").should eq("Hello World") | |
end | |
it "should return 'Hello Bob' when passed 'Bob'" do | |
hello("Bob").should eq("Hello Bob") | |
end | |
end | |
def hello(name) | |
"Hello #{name}" | |
end | |
def either_or(arg1, arg2, arg3) | |
if arg1 | |
arg2 | |
else | |
arg3 | |
end | |
end | |
def favorite_number(num1, num2) | |
if num1 > num2 | |
"Too low" | |
elsif num1 < num2 | |
"Too high" | |
else | |
"You got it!" | |
end | |
end | |
gets_discount = true | |
price *= 0.8 if gets_discount | |
skip_tax = true | |
price += price * 0.1 unless skip_tax | |
def is_true(a) | |
if a | |
"true" | |
else | |
"false" | |
end | |
end | |
is_true("hello") #=> will return "true" | |
is_true(4) #=> will return "true" | |
is_true(true) #=> will return "true" | |
is_true(nil) #=> will return "false" | |
is_true(false) #=> will return "false" | |
def who_am_i(people, schedule, task) | |
if schedule == 'night' && task == "computer" | |
:programmer | |
end | |
if people == 'adults' || people == 'kids' | |
:teacher | |
end | |
if people == 'collegues' && task == 'moleskine' | |
:manager | |
end | |
end | |
def who_am_i(people, schedule, task) | |
if schedule == 'night' && task == "computer" | |
:programmer | |
elsif people == 'collegues' && task == 'moleskine' | |
:manager | |
elsif people == 'adults' || people == 'kids' | |
:teacher | |
end | |
end | |
List | |
list = [] | |
list << 1 | |
list << "two" | |
list << :three | |
list << [4] | |
list #=> [1, "two", :three, [4]] | |
short way to present a array | |
items = %w(banana apple) | |
items_sorted = %w(apple banana) | |
#Class | |
class Car | |
def turn_on | |
"on" | |
end | |
end | |
ferrari = Car.new | |
ferrari.turn_on #=> "on" | |
# Hash | |
dictionary = { apple: "a red fruit", banana: "a yellow fruit", broccoli: "a green vegetable"} | |
puts dictionary[:apple] | |
#Ruby can automatically generate an Array of Strings from a whitespace-delimited list of words, using a special notation %w[]: | |
%w[the of and a] == ['the', 'of', 'and', 'a'] | |
# Yield | |
class Array | |
def new_each | |
0.upto(self.length - 1) do |index| | |
yield self[index] # yield invokes the block passed to it's containing method, and takes an argument. | |
end | |
end | |
end | |
[1,2,3,4].new_each { |num| puts "#{ num }!!!" } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Create and pass Proc objects | |
times_2 = Proc.new { |x| x*2 } | |
def apply_and_print(f, x) | |
puts f.call(x) | |
end | |
apply_and_print(times_2, 123) # 246 | |
=begin | |
A Proc object is, essentially, a lexically-scoped function object (similar to a function in Scheme). Which is conceptually and practically different from a method, because methods belong to an object, while functions are free logic not tied to anything. | |
It is slightly inconvenient to call this method, because a caller needs to explicitly create a Proc to pass. | |
An advantage of using explicit Proc objects like this is that, as objects, they're first-class citizens in Ruby and we can use them like any other object (eg, pass as many of them as we want, put them in variables, call other methods on them, pass them around further, etc). | |
=end | |
### Convert a passed block to a Proc object | |
def apply_and_print(x, &f) | |
puts f.call(x) | |
end | |
apply_and_print(123) { |x| x*2 } # 246 | |
=begin | |
&f converts a passed block to a Proc argument named f. Note that this must be the last argument listed, and there must only be 1 & argument, since and we can only pass 1 block to a method. | |
It is slightly more convenient to call this method, since a caller no longer has to explicitly create a Proc to pass. | |
An advantage of using an explicit Proc conversion a Proc can still be used as an independent object. | |
A disadvantage is that we can now only pass a single piece of external logic to the method (not usually a problem in Ruby... but that may itself be due to this restriction discouraging that type of code). | |
=end | |
### Calling a block with yield | |
def apply_and_print(x) | |
puts yield(x) | |
end | |
apply_and_print(123) { |x| x*2 } # 246 | |
=begin | |
yield passes its arguments to the given block, and returns the block's return value. It's kind-of like and aliased name for the block, to use the block as if it were a method. But blocks are not first-class in Ruby, they're not object. And since we've haven't converted the block into an Proc object in this version, we can't pass it to another method, or call any other methods on yield itself. We can only get its return value. | |
But it's definitely the most convenient to both write and call this method. | |
NOTE: Proc is lambda | |
A Proc can also be created using proc or lambda. Be careful though: lambda-created Proc objects have slightly different semantics. But the 3 methods (lambda, proc, and Proc.new) are almost completely interchangeable. | |
Procs are first-class objects, like any other in Ruby | |
=end | |
# We don't need to give a Proc a name (ie, assign it to a temporary variable); we can use it directly: | |
def apply_and_print(f, x) | |
puts f.call(x) | |
end | |
apply_and_print(Proc.new { |x| x*2 }, 123) # 246 | |
#More Example | |
class Array | |
def new_map | |
arr = [] | |
0.upto(self.length - 1) do |index| | |
arr << (yield self[index]) | |
end | |
arr | |
end | |
def new_map! | |
arr = [] | |
0.upto(self.length - 1) do |index| | |
arr << (yield self[index]) | |
end | |
arr | |
end | |
end | |
describe "Array" do | |
describe "new_map" do | |
it "should not call map" do | |
a = [1, 2, 3] | |
a.stub(:map) { '' } | |
a.new_map { |i| i + 1 }.should eq([2, 3, 4]) | |
end | |
it "should map any object" do | |
a = [1, "two", :three] | |
a.new_map { |i| i.class }.should eq([Fixnum, String, Symbol]) | |
end | |
end | |
describe "new_map!" do | |
it "should change the array" do | |
a = [1, 2, 3] | |
a.new_map! { |i| i + 1 } | |
a.should eq([2, 3, 4]) | |
end | |
it "should change the array for classes" do | |
a = [1, "two", :three] | |
a.new_map! { |i| i.class } | |
a.should eq([Fixnum, String, Symbol]) | |
end | |
end | |
end | |
class Array | |
def new_each | |
0.upto(self.length - 1) do |index| | |
yield self[index] # yield invokes the block passed to it's containing method, and takes an argument. | |
end | |
end | |
end | |
[1,2,3,4].new_each { |num| puts "#{ num }!!!" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment