Commit 9eabb055 by Mai Hoang Thai Ha

add exercise 1 to 44

parent af69e4e6
Pipeline #1182 failed with stages
in 0 seconds
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat
\ No newline at end of file
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
\ No newline at end of file
print "Give me a number: "
number = gets.chomp.to_i
bigger = number * 100
puts "A bigger number is #{bigger}."
print "Give me another number: "
another = gets.chomp
number = another.to_i
smaller = number / 100
puts "A smaller number is #{smaller}."
\ No newline at end of file
first, second, third = ARGV
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
\ No newline at end of file
user_name = ARGV.first # gets the first argument
prompt = '> '
puts "Hi #{user_name}."
puts "I'd like to ask you a few questions."
puts "Do you like me #{user_name}? "
puts prompt
likes = $stdin.gets.chomp
puts "Where do you live #{user_name}? "
puts prompt
lives = $stdin.gets.chomp
# a comma for puts is like using it twice
puts "What kind of computer do you have? ", prompt
computer = $stdin.gets.chomp
puts """
Alright, so you said #{likes} about liking me.
You live in #{lives}. Not sure where that is.
And you have a #{computer} computer. Nice.
"""
\ No newline at end of file
filename = ARGV.first
txt = open(filename)
puts "Here's your file #{filename}:"
print txt.read
print "Type the filename again: "
file_again = $stdin.gets.chomp
txt_again = open(file_again)
print txt_again.read
\ No newline at end of file
filename = ARGV.first
puts "We're going to erase #{filename}"
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that, hit RETURN."
$stdin.gets
puts "Opening the file..."
target = open(filename, 'w')
puts "Truncating the file. Goodbye!"
target.truncate(0)
puts "Now I'm going to ask you for three lines."
print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $stdin.gets.chomp
puts "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts "And finally, we close it."
target.close
\ No newline at end of file
from_file, to_file = ARGV
puts "Copying from #{from_file} to #{to_file}"
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read
puts "The input file is #{indata.length} bytes long"
puts "Does the output file exist? #{File.exist?(to_file)}"
puts "Ready, hit RETURN to continue, CTRL-C to abort."
$stdin.gets
out_file = open(to_file, 'w')
out_file.write(indata)
puts "Alright, all done."
out_file.close
in_file.close
\ No newline at end of file
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
puts "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
puts "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
\ No newline at end of file
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
puts "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
puts "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
\ No newline at end of file
# A comment, this is so you can read your program later.
# Anything after the # is ignored by ruby.
puts "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# puts "This won't run."
puts "This will run."
input_file = ARGV.first
def print_all(f)
puts f.read
end
def rewind(f)
f.seek(0)
end
def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"
end
current_file = open(input_file)
puts "First let's print the whole file:\n"
print_all(current_file)
puts "Now let's rewind, kind of like a tape."
rewind(current_file)
puts "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
\ No newline at end of file
def add(a, b)
puts "ADDING #{a} + #{b}"
return a + b
end
def subtract(a, b)
puts "SUBTRACTING #{a} - #{b}"
return a - b
end
def multiply(a, b)
puts "MULTIPLYING #{a} * #{b}"
return a * b
end
def divide(a, b)
puts "DIVIDING #{a} / #{b}"
return a / b
end
puts "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}"
# A puzzle for the extra credit, type it in anyway.
puts "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
puts "That becomes: #{what}. Can you do it by hand?"
\ No newline at end of file
puts "Let's practice everything."
puts 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
# the <<END is a "heredoc". See the Student Questions.
poem = <<END
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
END
puts "--------------"
puts poem
puts "--------------"
five = 10 - 2 + 3 - 6
puts "This should be five: #{five}"
def secret_formula(started)
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
end
start_point = 10000
beans, jars, crates = secret_formula(start_point)
puts "With a starting point of: #{start_point}"
puts "We'd have #{beans} beans, #{jars} jars, and #{crates} crates."
start_point = start_point / 10
puts "We can also do that this way:"
puts "We'd have %s beans, %d jars, and %d crates." % secret_formula(start_point)
\ No newline at end of file
module Ex25
# This function will break up words for us.
def Ex25.break_words(stuff)
words = stuff.split(' ')
return words
end
# Sorts the words.
def Ex25.sort_words(words)
return words.sort
end
# Prints the first word after shifting it off.
def Ex25.print_first_word(words)
word = words.shift
puts word
end
# Prints the last word after popping it off.
def Ex25.print_last_word(words)
word = words.pop
puts word
end
# Takes in a full sentence and returns the sorted words.
def Ex25.sort_sentence(sentence)
words = Ex25.break_words(sentence)
return Ex25.sort_words(words)
end
# Prints the first and last words of the sentence.
def Ex25.print_first_and_last(sentence)
words = Ex25.break_words(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
# Sorts the words then prints the first and last one.
def Ex25.print_first_and_last_sorted(sentence)
words = Ex25.sort_sentence(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
end
# >>> irb
# require "./ex25.rb"
# sentence = "All good things come to those who wait."
# words = Ex25.break_words(sentence)
# words
# sorted_words = Ex25.sort_words(words)
# sorted_words
# Ex25.print_first_word(words)
# Ex25.print_last_word(words)
# words
# Ex25.print_first_word(sorted_words)
# Ex25.print_last_word(sorted_words)
# sorted_words
# sorted_words = Ex25.sort_sentence(sentence)
# sorted_words
# Ex25.print_first_and_last(sentence)
# Ex25.print_first_and_last_sorted(sentence)
\ No newline at end of file
module Ex25
# This function will break up words for us.
def Ex25.break_words(stuff)
words = stuff.split(' ')
return words
end
# Sorts the words.
def Ex25.sort_words(words)
return words.sort
end
# Prints the first word after popping it off.
def Ex25.print_first_word(words)
word = words.shift
puts word
end
# Prints the last word after popping it off.
def Ex25.print_last_word(words)
word = words.pop
puts word
end
# Takes in a full sentence and returns the sorted words.
def Ex25.sort_sentence(sentence)
words = Ex25.break_words(sentence)
return Ex25.sort_words(words)
end
# Prints the first and last words of the sentence.
def Ex25.print_first_and_last(sentence)
words = Ex25.break_words(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
# Sorts the words then prints the first and last one.
def Ex25.print_first_and_last_sorted(sentence)
words = Ex25.sort_sentence(sentence)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
end
end
puts "Let's practice everything."
puts 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
poem = <<END
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
END
puts "--------------"
puts poem
puts "--------------"
five = 10 - 2 + 3 - 6
puts "This should be five: #{five}"
def secret_formula(started)
jelly_beans = started * 500
jars = jelly_beans / 1000
crate = jars / 100
return jelly_beans, jars, crate
end
start_point = 10000
beans, jars, crates = secret_formula(start_point)
puts "With a starting point of: #{start_point}"
puts "We'd have #{beans}, #{jars} jars, and #{crates} crates."
start_point = start_point / 10
puts "we can also do that this way:"
puts "We'd have %s beans, %d jars and %d crates." % secret_formula(start_point)
sentence = "All good things come to those who wait."
words = Ex25.break_words(sentence)
sorted_words = Ex25.sort_words(words)
Ex25.print_first_word(words)
Ex25.print_last_word(words)
Ex25.print_first_word(sorted_words)
Ex25.print_last_word(sorted_words)
# sorted_words = Ex25.sort_sentence(sentence)
Ex25.print_first_and_last(sentence)
Ex25.print_first_and_last_sorted(sentence)
\ No newline at end of file
# NOT true?
# !false true
# !true false
# OR (||) true?
# true || false true
# true || true true
# false || true true
# false || false false
# AND (&&) true?
# true && false false
# true && true true
# false && true false
# false && false false
# NOT OR true?
# not (true || false) false
# not (true || true) false
# not (false || true) false
# not (false || false) true
# NOT AND true?
# !(true && false) true
# !(true && true) false
# !(false && true) true
# !(false && false) true
# != true?
# 1 != 0 true
# 1 != 1 false
# 0 != 1 true
# 0 != 0 false
# == true?
# 1 == 0 false
# 1 == 1 true
# 0 == 1 false
# 0 == 0 true
\ No newline at end of file
# true && true
# false && true
# 1 == 1 && 2 == 1
# "test" == "test"
# 1 == 1 || 2 != 1
# true && 1 == 1
# false && 0 != 0
# true || 1 == 1
# "test" == "testing"
# 1 != 0 && 2 == 1
# "test" != "testing"
# "test" == 1
# !(true && false)
# !(1 == 1 && 0 != 1)
# !(10 == 1 || 1000 == 1000)
# !(1 != 10 || 3 == 4)
# !("testing" == "testing" && "Zed" == "Cool Guy")
# 1 == 1 && (!("testing" == 1 || 1 == 0))
# "chunky" == "bacon" && (!(3 == 4 || 3 == 3))
# 3 == 3 && (!("testing" == "testing" || "Ruby" == "Fun"))
\ No newline at end of file
people = 20000
cats = 30
dogs = 15
if people < cats
puts "Too many cats! The world is doomed!"
end
if people > cats
puts "Not many cats! The world is saved!"
end
if people < dogs
puts "The world is drooled on!"
end
if people > dogs
puts "The world is dry!"
end
dogs += 5
if people >= dogs
puts "People are greater than or equal to dogs."
end
if people <= dogs
puts "People are less than or equal to dogs."
end
if people == dogs
puts "People are dogs."
end
\ No newline at end of file
puts "I will now count my chickens:"
# phep chia vd 10 / 3 = 3
# muon co phan thap phan thi 10.0 / 3 hoac 10/3.0 = 3.3333
puts "Hens #{25 + 30 / 6}"
puts "Roosters #{100 - 25 * 3 % 4}"
puts "Now I will count the eggs:"
puts 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
puts "Is it true that 3 + 2 < 5 - 7?"
puts 3 + 2 < 5 - 7
puts "What is 3 + 2? #{3 + 2}"
puts "What is 5 - 7? #{5 - 7}"
puts "Oh, that's why it's false."
puts "How about some more."
puts "Is it greater? #{5 > -2}"
puts "Is it greater or equal? #{5 >= -2}"
puts "Is it less or equal? #{5 <= -2}"
\ No newline at end of file
people = 30
cars = 40
trucks = 15
if cars > people
puts "We should take the cars."
elsif cars < people
puts "We should not take the cars."
else
puts "We can't decide."
end
if trucks > cars
puts "That's too many trucks."
elsif trucks < cars
puts "Maybe we could take the trucks."
else
puts "We still can't decide."
end
if people > trucks
puts "Alright, let's just take the trucks."
else
puts "Fine, let's stay home then."
end
\ No newline at end of file
user_name = ARGV.first
prompt = ">>>"
puts "welcome #{user_name} to Borderlands"
puts '-------------------------------'
puts "You enter the Land of the Dead. There's only one way to survive"
puts "type 1 to start or if you are scared can escape by typing 2"
print "#{prompt}"
s1 = $stdin.gets.chomp
if s1 == "1"
puts "Meet Surtur!"
puts "1. Fight him."
puts "2. seek shelter."
print "#{prompt} "
s2 = $stdin.gets.chomp
if s2 == "1"
puts "surtur has been defeated by you"
puts "Congratulations. You win"
elsif s2 == "2"
puts "you have been caught by surtur. YOU DEAD!!!!!!!"
else
puts "you entered the wrong syntax. YOU DEAD!!!!!!!"
end
elsif s1 == "2"
puts "you are a coward! Surtur has killed you"
else
puts "you entered the wrong syntax. YOU DEAD!!!!!!!"
end
#for and each
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
# in a more traditional style found in other languages
for number in the_count
puts "This is count #{number}"
end
# same as above, but in a more Ruby style
# this and the next one are the preferred
# way Ruby for-loops are written
fruits.each do |fruit|
puts "A fruit of type: #{fruit}"
end
# also we can go through mixed lists too
# note this is yet another style, exactly like above
# but a different syntax (way to write it).
change.each {|i| puts "I got #{i}" }
# we can also build lists, first start with an empty one
elements = []
# then use the range operator to do 0 to 5 counts
(0..5).each do |i|
puts "adding #{i} to the list."
# pushes the i variable on the *end* of the list
elements.push(i)
end
print "elements = #{elements} \n" # print arr khac puts arr
# now we can print them out too
elements.each {|i| puts "Element was: #{i}" }
\ No newline at end of file
#while loop
i = 0
numbers = []
# while i < 6
# puts "At the top i is #{i}" # i = i
# numbers.push(i)
# i += 1
# puts "Numbers now: ", numbers
# puts "At the bottom i is #{i}" # i += 1
# end
# puts "The numbers: "
# remember you can write this 2 other ways?
# numbers.each {|num| puts num }
(0..5).each do |a|
puts "At the top i is #{a}" # i = i
numbers.push(a)
puts "Numbers now: ", numbers
puts "At the bottom i is #{a + 1}" # i += i
end
\ No newline at end of file
animals = ['bear', 'tiger', 'penguin', 'zebra']
number = ['1', '2', '3', '4', '5']
students = ['John', 'Hanah', 'Wayne', 'Michael', 'Sarah']
puts "animal index 0 is #{bear = animals[0]}"
def element_of_array (arr)
print "Nhap phan tu ban muon lay: "
i = $stdin.gets.chomp.to_i
if i > arr.length
puts "Phan tu vuot qua do dai cua mang"
else
puts "phan tu thu #{i} trong mang nay la: #{element = arr[i]}"
end
return element
end
element_of_array(students)
element_of_array(animals)
\ No newline at end of file
def gold_room
puts "This room is full of gold. How much do you take?"
print "> "
choice = $stdin.gets.chomp
# this line has a bug, so fix it
if choice.to_i.to_s == choice
how_much = choice.to_i
else
dead("Man, learn to type a number.")
end
if how_much < 50
puts "Nice, you're not greedy, you win!"
exit(0)
else
dead("You greedy bastard!")
end
end
def bear_room
puts "There is a bear here."
puts "The bear has a bunch of honey."
puts "The fat bear is in front of another door."
puts "How are you going to move the bear?"
bear_moved = false
while true
print "> "
choice = $stdin.gets.chomp
if choice == "take honey"
dead("The bear looks at you then slaps your face off.")
elsif choice == "taunt bear" && !bear_moved
puts "The bear has moved from the door. You can go through it now."
bear_moved = true
elsif choice == "taunt bear" && bear_moved
dead("The bear gets pissed off and chews your leg off.")
elsif choice == "open door" && bear_moved
gold_room
else
puts "I got no idea what that means."
end
end
end
def cthulhu_room
puts "Here you see the great evil Cthulhu."
puts "He, it, whatever stares at you and you go insane."
puts "Do you flee for your life or eat your head?"
print "> "
choice = $stdin.gets.chomp
if choice.include? "flee"
start
elsif choice.include? "head"
dead("Well that was tasty!")
else
cthulhu_room
end
end
def dead(why)
puts why, "Good job!"
exit(0)
end
def start
puts "You are in a dark room."
puts "There is a door to your right and left."
puts "Which one do you take?"
print "> "
choice = $stdin.gets.chomp
if choice == "left"
bear_room
elsif choice == "right"
cthulhu_room
else
dead("You stumble around the room until you starve.")
end
end
# start
gold_room
# create a mini game
def game_over(why)
puts why, 'Good job!'
exit(0)
end
def win
puts 'Congratulation!!! YOU WIN.'
exit(0)
end
def next_question(question)
if question == 'question_1'
question_2
elsif question == 'question_2'
question_3
elsif question == 'question_3'
question_4
elsif question == 'question_4'
question_5
elsif question == 'question_5'
win
end
end
def question_1
puts %( Questions 1. Which is not a programming language?
\tA. Ruby
\tB. Javascript
\tC. HTML
\tD. Python
)
correct = false
while true
print '>'
answer = $stdin.gets.chomp
if %w[a A].include?(answer)
game_over('uncorrect')
elsif %w[b B].include?(answer)
game_over('uncorrect')
elsif %w[c C].include?(answer)
correct = true
puts 'Exactly, go to question 2'
question_2
elsif %w[d D].include?(answer)
game_over('uncorrect')
elsif answer == '0'
correct = true
next_question('question_1')
else
puts 'you entered the wrong syntax'
end
end
end
def question_2
puts %(Question2. What is the result of the expression "10/3" in ruby ​​language?
\tA. 3
\tB. 3.3333
\tC. nil
\tD. 1
)
correct = false
while true
print '>'
answer = $stdin.gets.chomp
if %w[a A].include?(answer)
correct = true
puts 'Exactly, go to question 2'
question_3
elsif %w[b B].include?(answer)
game_over('uncorrect')
elsif %w[c C].include?(answer)
game_over('uncorrect')
elsif %w[d D].include?(answer)
game_over('uncorrect')
elsif answer == '0'
correct = true
next_question('question_2')
else
puts 'you entered the wrong syntax'
end
end
end
def question_3
puts %(Questions 3. how many days in May?
\tA. 30 days
\tB. 28 days
\tC. nothing
\tD. 31 days
)
correct = false
while true
print '>'
answer = $stdin.gets.chomp
if %w[a A].include?(answer)
game_over('uncorrect')
elsif %w[b B].include?(answer)
game_over('uncorrect')
elsif %w[c C].include?(answer)
game_over('uncorrect')
elsif %w[d D].include?(answer)
correct = true
puts 'Exactly, go to question 4'
question_4
elsif answer == '0'
correct = true
next_question('question_3')
else
puts 'you entered the wrong syntax'
end
end
end
def question_4
puts %(Questions 4. How long will it take for every year to have 366 days in it?
\tA. 1
\tB. 9
\tC. 4
\tD. 100
)
correct = false
while true
print '>'
answer = $stdin.gets.chomp
if %w[a A].include?(answer)
game_over('uncorrect')
elsif %w[b B].include?(answer)
game_over('uncorrect')
elsif %w[c C].include?(answer)
correct = true
puts 'Exactly, go to question 5'
question_5
elsif %w[d D].include?(answer)
game_over('uncorrect')
elsif answer == '0'
correct = true
next_question('question_4')
else
puts 'you entered the wrong syntax'
end
end
end
def question_5
puts %( Questions 5. What animals can fly?
\tA. Bird
\tB. Crocodile
\tC. Dog
\tD. Chicken
)
correct = false
while true
print '>'
answer = $stdin.gets.chomp
if %w[a A].include?(answer)
correct = true
puts 'Excellent'
win
elsif %w[b B].include?(answer)
game_over('uncorrect')
elsif %w[c C].include?(answer)
game_over('uncorrect')
elsif %w[d D].include?(answer)
game_over('uncorrect')
elsif answer == '0'
correct = true
next_question('question_5')
else
puts 'you entered the wrong syntax'
end
end
end
def start
puts 'Welcome to the puzzle game'
puts 'you have 5 questions. to pass question type 0'
puts 'are you ready?(y/n)'
print '>'
choice = $stdin.gets.chomp
if choice == 'y'
question_1
else
game_over('See you again')
end
end
start
# Keyword Description Example
# BEGIN Run this block when the script starts. BEGIN { puts "hi" }
# END Run this block when the script is done. END { puts "hi" }
# alias Create another name for a function. alias X Y
# and Logical and, but lower priority than &&. puts "Hello" and "Goodbye"
# begin Start a block, usually for exceptions. begin end
# break Break out of a loop right now. while true; break; end
# case Case style conditional, like an if. case X; when Y; else; end
# class Define a new class. class X; end
# def Define a new function. def X(); end
# defined? Is this class/function/etc. defined already? defined? Class == "constant"
# do Create a block that maybe takes a parameter. (0..5).each do |x| puts x end
# else Else conditional. if X; else; end
# elsif Else if conditional if X; elsif Y; else; end
# end Ends blocks, functions, classes, everything. begin end # many others
# ensure Run this code whether an exception happens or not. begin ensure end
# for For loop syntax. The .each syntax is preferred. for X in Y; end
# if If conditional. if X; end
# in In part of for-loops. for X in Y; end
# module Define a new module. module X; end
# next Skip to the next element of a .each iterator. (0..5).each {|y| next }
# not Logical not. But use ! instead. not true == false
# or Logical or. puts "Hello" or "Goodbye"
# redo Rerun a code block exactly the same. (0..5).each {|i| redo if i > 2}
# rescue Run this code if an exception happens. begin rescue X; end
# retry In a rescue clause, says to try the block again. (0..5).each {|i| retry if i > 2}
# return Returns a value from a function. Mostly optional. return X
# self The current object, class, or module. defined? self == "self"
# super The parent class of this class. super
# then Can be used with if optionally. if true then puts "hi" end
# undef Remove a function definition from a class. undef X
# unless Inverse of if. unless false then puts "not" end
# until Inverse of while, execute block as long as false. until false; end
# when Part of case conditionals. case X; when Y; else; end
# while While loop. while true; end
# yield Pause and transfer control to the code block. yield
# DATA TYPE
# Type Description Example
# true True boolean value. true or false == true
# false False boolean value. false and true == false
# nil Represents "nothing" or "no value". x = nil
# strings Stores textual information. x = "hello"
# numbers Stores integers. i = 100
# floats Stores decimals. i = 10.389
# arrays Stores a list of things. j = [1,2,3,4]
# hashes Stores a key=value mapping of things. e = {'x' => 1, 'y' => 2}
# String Escape Sequences
# Escape Description
# \\ Backslash
# \' Single-quote
# \" Double-quote
# \a Bell
# \b Backspace
# \f Formfeed
# \n Newline
# \r Carriage
# \t Tab
# \v Vertical tab
# Operators
# Operator Description Example
# + Add 2 + 4 == 6
# - Subtract 2 - 4 == -2
# * Multiply 2 * 4 == 8
# ** Power of 2 ** 4 == 16
# / Divide 2 / 4.0 == 0.5
# % Modulus 2 % 4 == 2
# > Greater than 4 > 4 == false
# . Dot access "1".to_i == 1
# :: Colon access Module::Class
# [] List brackets [1,2,3,4]
# ! Not !true == false
# < Less than 4 < 4 == false
# > Greater than 4 < 4 == false
# >= Greater than equal 4 >= 4 == true
# <= Less than equal 4 <= 4 == true
# <=> Comparison 4 <=> 4 == 0
# == Equal 4 == 4 == true
# === Equality 4 === 4 == true
# != Not equal 4 != 4 == false
# && Logical and (higher precedence) true && false == false
# || Logical or (higher precedence) true || false == true
# .. Range inclusive (0..3).to_a == [0, 1, 2, 3]
# ... Range non-inclusive (0...3).to_a == [0, 1, 2]
# @ Object scope @var ; @@classvar
# @@ Class scope @var ; @@classvar
# $ Global scope $stdin
ten_things = "Apples Oranges Crows Telephone Light Sugar"
puts "Wait there are not 10 things in that list. Let's fix that."
#chuyen doi chuoi thanh arr ["Apples", "Oranges", "Crows", "Telephone", "Light", "Sugar"]
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
# using math to make sure there's 10 items
while stuff.length != 10
next_one = more_stuff.pop
puts "Adding: #{next_one}"
stuff.push(next_one)
puts "There are #{stuff.length} items now."
end
puts "There we go: #{stuff}"
puts "Let's do some things with stuff."
puts stuff[1]
puts stuff[-1] # whoa! fancy
puts stuff.pop()
puts stuff.join(' ')
puts stuff[3...5].join("#")
student = {
'Ha' => 'HA',
'Thanh' => 'TH',
'Trong' => 'TR',
'Hoa' => 'HO',
'Hao' => 'AO',
20 => 'ZO'
}
pro_language = {
'HA' => 'Ruby',
'TH' => 'Js',
'TR' => 'PHP',
'HO' => 'Python',
'AO' => 'Swift'
}
puts pro_language[student['Ha']]
student.each do |s, abb|
puts "#{s} is a #{abb}"
end
student.each do |s, abb|
pl = pro_language[abb]
puts "#{s} is abbreviated #{abb} and has program language #{pl}"
end
def kiem_tra_ma_sv (list)
puts 'nhap ten sinh vien can xem'
student_name = $stdin.gets.chomp # tra ve kieu du lieu string
if !list[student_name]
puts "xin loi k co sinh vien nay"
else
puts "ma so sv la #{list[student_name]}"
end
end
kiem_tra_ma_sv(student)
\ No newline at end of file
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
puts "There are #{cars} cars available."
puts "There are only #{drivers} drivers available."
puts "There will be #{cars_not_driven} empty cars today."
puts "We can transport #{carpool_capacity} people today."
puts "We have #{passengers} to carpool today."
puts "We need to put about #{average_passengers_per_car} in each car."
\ No newline at end of file
class Song
def initialize(lyrics)
@lyrics = lyrics
end
def sing_me_a_song()
@lyrics.each {|line| puts line }
end
end
happy_bday = Song.new(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song.new(["They rally around tha family",
"With pockets full of shells"])
# print happy_bday.initialize
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
class Name
def initialize(name)
@name = name
end
def call_the_name()
@name.each {|n| puts n}
end
end
student = Name.new(['ha', 'thanh', 'trong', 'hoa', 'hao'])
student.call_the_name
# class MyStuff
# def initialize()
# @tangerine = "And now a thousand years between"
# end
# attr_reader :tangerine
# def apple()
# puts "I AM CLASSY APPLES!"
# end
# end
# thing = MyStuff.new()
# # MyStuff.apple
# thing.apple
# puts thing.tangerine
\ No newline at end of file
require 'open-uri'
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class ### < ###\nend" =>
"Make a class named ### that is-a ###.",
"class ###\n\tdef initialize(@@@)\n\tend\nend" =>
"class ### has-a initialize that takes @@@ parameters.",
"class ###\n\tdef ***(@@@)\n\tend\nend" =>
"class ### has-a function named *** that takes @@@ parameters.",
"*** = ###.new()" =>
"Set *** to an instance of class ###.",
"***.***(@@@)" =>
"From *** get the *** function, and call it with parameters @@@.",
"***.*** = '***'" =>
"From *** get the *** attribute and set it to '***'."
}
PHRASE_FIRST = ARGV[0] == "english"
open(WORD_URL) {|f|
f.each_line {|word| WORDS.push(word.chomp)}
}
def craft_names(rand_words, snippet, pattern, caps=false)
names = snippet.scan(pattern).map do
word = rand_words.pop()
caps ? word.capitalize : word
end
return names * 2
end
def craft_params(rand_words, snippet, pattern)
names = (0...snippet.scan(pattern).length).map do
param_count = rand(3) + 1
params = (0...param_count).map {|x| rand_words.pop() }
params.join(', ')
end
return names * 2
end
def convert(snippet, phrase)
rand_words = WORDS.sort_by {rand}
class_names = craft_names(rand_words, snippet, /###/, caps=true)
other_names = craft_names(rand_words, snippet, /\*\*\*/)
param_names = craft_params(rand_words, snippet, /@@@/)
results = []
[snippet, phrase].each do |sentence|
# fake class names, also copies sentence
result = sentence.gsub(/###/) {|x| class_names.pop }
# fake other names
result.gsub!(/\*\*\*/) {|x| other_names.pop }
# fake parameter lists
result.gsub!(/@@@/) {|x| param_names.pop }
results.push(result)
end
return results
end
# keep going until they hit CTRL-D
loop do
snippets = PHRASES.keys().sort_by {rand}
for snippet in snippets
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST
question, answer = answer, question
end
print question, "\n\n> "
exit(0) unless $stdin.gets
puts "\nANSWER: %s\n\n" % answer
end
end
\ No newline at end of file
## Animal is-a object look at the extra credit
class Animal
end
## Dog is-a Animal
class Dog < Animal
def initialize(name)
## Khoi tao name
@name = name
end
def call_name()
puts "Name of the dog: #{@name}"
end
end
## Cat is-a Animal
class Cat < Animal
def initialize(name)
## khoi tao name
@name = name
end
end
## ??
class Person
def initialize(name)
## ??
@name = name
## Person has-a pet of some kind
@pet = nil
end
attr_accessor :pet
end
## Person has-a Employee #thua ke
class Employee < Person
def initialize(name, salary)
## ?? hmm what is this strange magic?
super(name)
## ??
@salary = salary
end
end
## ??
class Fish
end
## Fish has-a Salmon #thua ke
class Salmon < Fish
end
## Fish has-a Halibut #thua ke
class Halibut < Fish
end
## rover is-a Dog
rover = Dog.new("Rover")
## satan is-a Cat
satan = Cat.new("Satan")
## mary is-a Person
mary = Person.new("Mary")
## mary has-a pet(satan)
mary.pet = satan
## frank is-a Person, has-a name and salary
frank = Employee.new("Frank", 120000)
## frank has-a pet(rover)
frank.pet = rover
## flipper is a Fish
flipper = Fish.new()
## Fish has-a Salmon, crouse is-a Salmon
crouse = Salmon.new()
## Fish has a Halibut, harru is-a Halibut
harry = Halibut.new()
puts rover.call_name
\ No newline at end of file
class Scene
def enter()
puts "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
end
end
class Engine
def initialize(scene_map)
@scene_map = scene_map
end
def play()
current_scene = @scene_map.opening_scene()
last_scene = @scene_map.next_scene('finished')
while current_scene != last_scene
next_scene_name = current_scene.enter()
current_scene = @scene_map.next_scene(next_scene_name)
end
# be sure to print out the last scene
current_scene.enter()
end
end
class Death < Scene
@@quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter()
puts @@quips[rand(0..(@@quips.length - 1))]
exit(1)
end
end
class CentralCorridor < Scene
def enter()
puts "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
puts "your entire crew. You are the last surviving member and your last"
puts "mission is to get the neutron destruct bomb from the Weapons Armory,"
puts "put it in the bridge, and blow the ship up after getting into an "
puts "escape pod."
puts "\n"
puts "You're running down the central corridor to the Weapons Armory when"
puts "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
puts "flowing around his hate filled body. He's blocking the door to the"
puts "Armory and about to pull a weapon to blast you."
print "> "
action = $stdin.gets.chomp
if action == "shoot!"
puts "Quick on the draw you yank out your blaster and fire it at the Gothon."
puts "His clown costume is flowing and moving around his body, which throws"
puts "off your aim. Your laser hits his costume but misses him entirely. This"
puts "completely ruins his brand new costume his mother bought him, which"
puts "makes him fly into an insane rage and blast you repeatedly in the face until"
puts "you are dead. Then he eats you."
return 'death'
elsif action == "dodge!"
puts "Like a world class boxer you dodge, weave, slip and slide right"
puts "as the Gothon's blaster cranks a laser past your head."
puts "In the middle of your artful dodge your foot slips and you"
puts "bang your head on the metal wall and pass out."
puts "You wake up shortly after only to die as the Gothon stomps on"
puts "your head and eats you."
return 'death'
elsif action == "tell a joke"
puts "Lucky for you they made you learn Gothon insults in the academy."
puts "You tell the one Gothon joke you know:"
puts "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
puts "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
puts "While he's laughing you run up and shoot him square in the head"
puts "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else
puts "DOES NOT COMPUTE!"
return 'central_corridor'
end
end
end
class LaserWeaponArmory < Scene
def enter()
puts "You do a dive roll into the Weapon Armory, crouch and scan the room"
puts "for more Gothons that might be hiding. It's dead quiet, too quiet."
puts "You stand up and run to the far side of the room and find the"
puts "neutron bomb in its container. There's a keypad lock on the box"
puts "and you need the code to get the bomb out. If you get the code"
puts "wrong 10 times then the lock closes forever and you can't"
puts "get the bomb. The code is 3 digits."
code = "#{rand(1..9)}#{rand(1..9)}#{rand(1..9)}"
print "[keypad]> "
guess = $stdin.gets.chomp
guesses = 0
while guess != code && guesses < 10
puts "BZZZZEDDD!"
guesses += 1
print "[keypad]> "
guess = $stdin.gets.chomp
end
if guess == code
puts "The container clicks open and the seal breaks, letting gas out."
puts "You grab the neutron bomb and run as fast as you can to the"
puts "bridge where you must place it in the right spot."
return 'the_bridge'
else
puts "The lock buzzes one last time and then you hear a sickening"
puts "melting sound as the mechanism is fused together."
puts "You decide to sit there, and finally the Gothons blow up the"
puts "ship from their ship and you die."
return 'death'
end
end
end
class TheBridge < Scene
def enter()
puts "You burst onto the Bridge with the netron destruct bomb"
puts "under your arm and surprise 5 Gothons who are trying to"
puts "take control of the ship. Each of them has an even uglier"
puts "clown costume than the last. They haven't pulled their"
puts "weapons out yet, as they see the active bomb under your"
puts "arm and don't want to set it off."
print "> "
action = $stdin.gets.chomp
if action == "throw the bomb"
puts "In a panic you throw the bomb at the group of Gothons"
puts "and make a leap for the door. Right as you drop it a"
puts "Gothon shoots you right in the back killing you."
puts "As you die you see another Gothon frantically try to disarm"
puts "the bomb. You die knowing they will probably blow up when"
puts "it goes off."
return 'death'
elsif action == "slowly place the bomb"
puts "You point your blaster at the bomb under your arm"
puts "and the Gothons put their hands up and start to sweat."
puts "You inch backward to the door, open it, and then carefully"
puts "place the bomb on the floor, pointing your blaster at it."
puts "You then jump back through the door, punch the close button"
puts "and blast the lock so the Gothons can't get out."
puts "Now that the bomb is placed you run to the escape pod to"
puts "get off this tin can."
return 'escape_pod'
else
puts "DOES NOT COMPUTE!"
return "the_bridge"
end
end
end
class EscapePod < Scene
def enter()
puts "You rush through the ship desperately trying to make it to"
puts "the escape pod before the whole ship explodes. It seems like"
puts "hardly any Gothons are on the ship, so your run is clear of"
puts "interference. You get to the chamber with the escape pods, and"
puts "now need to pick one to take. Some of them could be damaged"
puts "but you don't have time to look. There's 5 pods, which one"
puts "do you take?"
good_pod = rand(1..5)
print "[pod #]> "
guess = $stdin.gets.chomp.to_i
if guess != good_pod
puts "You jump into pod %s and hit the eject button." % guess
puts "The pod escapes out into the void of space, then"
puts "implodes as the hull ruptures, crushing your body"
puts "into jam jelly."
return 'death'
else
puts "You jump into pod %s and hit the eject button." % guess
puts "The pod easily slides out into space heading to"
puts "the planet below. As it flies to the planet, you look"
puts "back and see your ship implode then explode like a"
puts "bright star, taking out the Gothon ship at the same"
puts "time. You won!"
return 'finished'
end
end
end
class Finished < Scene
def enter()
puts "You won! Good job."
end
end
class Map
@@scenes = {
'central_corridor' => CentralCorridor.new(),
'laser_weapon_armory' => LaserWeaponArmory.new(),
'the_bridge' => TheBridge.new(),
'escape_pod' => EscapePod.new(),
'death' => Death.new(),
'finished' => Finished.new(),
}
def initialize(start_scene)
@start_scene = start_scene
end
def next_scene(scene_name)
val = @@scenes[scene_name]
return val
end
def opening_scene()
return next_scene(@start_scene)
end
end
a_map = Map.new('central_corridor')
a_game = Engine.new(a_map)
a_game.play()
\ No newline at end of file
class Parent
def initialize(stuff)
@stuff = stuff
end
def override()
puts "PARENT override()"
end
def implicit()
puts "PARENT implicit()"
end
def altered()
puts "PARENT altered()"
end
end
class Child < Parent
def initialize(stuff)
@stuff = stuff
super()
end
def override()
puts "CHILD override()"
end
def altered()
puts "CHILD, BEFORE PARENT altered()"
super()
puts "CHILD, AFTER PARENT altered()"
end
end
dad = Parent.new('hello')
son = Child.new()
# dad.implicit()
# son.implicit()
# dad.override()
# son.override()
# dad.altered()
# son.altered()
\ No newline at end of file
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie in 2009
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
puts "Let's talk about #{my_name}."
puts "He's #{my_height} inches tall."
puts "He's #{my_weight} pounds heavy."
puts "Actually that's not too heavy."
puts "He's got #{my_eyes} eyes and #{my_hair} hair."
puts "His teeth are usually #{my_teeth} depending on the coffee."
# this line is tricky, try to get it exactly right
puts "If I add #{my_age}, #{my_height}, and #{my_weight} I get #{my_age + my_height + my_weight}."
\ No newline at end of file
types_of_people = 10
x = "There are #{types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = "Those who know #{binary} and those who #{do_not}."
puts x
puts y
puts "I said: #{x}."
puts "I also said: '#{y}'."
hilarious = false
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"
puts joke_evaluation
w = "This is the left side of..."
e = "a string with a right side."
puts w + e
puts "Mary had a little lamb."
puts "Its fleece was white as #{'snow'}."
puts "And everywhere that Mary went."
puts "." * 10 # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that print vs. puts on this line what's it do?
print end1 + end2 + end3 + end4 + end5 + end6
puts end7 + end8 + end9 + end10 + end11 + end12
\ No newline at end of file
formatter = "%{first} %{second} %{third} %{fourth}"
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}
puts formatter % {
first: "I had this thing.",
second: "That you could type up right.",
third: "But it didn't sing.",
fourth: "So I said goodnight."
}
\ No newline at end of file
# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: #{days}"
puts "Here are the months: #{months}"
puts %q{
There's something going on here.
With this weird quote
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
}
\ No newline at end of file
ruby-training @ af69e4e6
Subproject commit af69e4e6b7e55bdfc85555c131cab828bf7775b9
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment