ruby Ruby基础知识
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby基础知识相关的知识,希望对你有一定的参考价值。
=begin
#Methods
to_s converts values to strings.
to_i converts values to integers (numbers.)
to_a converts values to arrays.
=end
#to reverse method
"priss".reverse
40.to_s.reverse
#array - max method in numbers
[12, 47, 35].max
#create a variable call ticket
ticket = [12, 47, 35]
#just type ticket and the value appear as a result
ticket
[12, 47, 35]
#ticket.sort!
#the exclamation is just signals that we intend for Ruby to directly modify the same
#array that we've built, rather than make a brand new copy that is sorted.
ticket.sort!
[12, 35, 47]
#print poenm and change a word
print poem
poem['toast'] = 'honeydew'
# [ ] mean "I'm looking for"
#poem reverse in each line
#you turned the poem into a list using lines.to_a.
#lines component decided the way the string should be split up, and then one of our "to" methods,
#to_a, converted those splits into an Array. (to_array.)
poem.lines.to_a.reverse
#Exclamation Points : Methods may have exclamation points in their name, which just means to impact the current data, rather than making a copy. No big deal.
#Square Brackets : With these, you can target and find things. You can even replace them if necessary.
#Chaining : methods lets you get a lot more done in a single command. Break up a poem, reverse it, reassemble it: poem.lines.to_a.reverse.join.
poem.include? "my hand"
=> true
#books
books = {}
#You've made an empty hash, also known as: a dictionary. Hashes store related information by giving reusable labels to pieces of our data.
#We're going to stuff some miniature book reviews in this hash. Here's our rating system:
#:splendid → a masterpiece.
#:quite_good → enjoyed, sure, yes.
#:mediocre → equal parts great and terrible.
#:quite_not_good → notably bad.
#:abysmal → steaming wreck.
#To rate a book, put the title in square brackets and put the rating after the equals.
#For example: books["Gravity's Rainbow"] = :splendid
# : symbol
#Notice that these ratings are not strings. When you place a colon in front of a simple word, you get a Ruby symbol. Symbols are much cheaper than strings (in terms of computer memory.) If you need to use a word over and over in your program itself, use a symbol. Rather than having thousands of copies of that word in memory, the computer will store a symbol only once, and refer to it over and over.
#build an empty hash
ratings = Hash.new(0)
books.values.each { |rate| ratings[rate] += 1 }
#(That | in the code is called the pipe character. It's probably located right above the Enter key on your keyboard.)
#This code will turn all your unique values in books...into keys within the new ratingshash. Crazy, right? Then, as it looks at each rating you originally gave in books, it will increase the count value for that rating in ratings
# After you've built your new hash of count values, type ratings again to see the full tally. This new hash will show you a rating followed by the number of times you've given that rating.
# A block is a chunk of Ruby code surrounded by curly braces
5.times { print "Odelay!" }
# Hashes : The little 'dictionary' with the curly braces: {}.
# Symbols : Tiny, efficiently reusable code words with a colon: :splendid.
# Blocks : Chunks of code which can be tacked on to many of Ruby's methods. Here's the code you used to build a scorecard: books.values.each { |rate| ratings[rate] += 1 }.
# Dir.entries "/" -- Anything listed after a method is considered an 'attachment'.
# print poem -- See, print is just an ordinary method, while the poem is what got attached for printing.
# print "pre", "event", "ual", "ism" -- This bit has several arguments! Ruby makes us use commas to distinguish between them.
# list just text files
Dir["/*.txt"]
# [ ] mean "I'm looking for"
# I am looking for any files which end with .txt." The asterisk indicates the "any file" part.
print File.read("/comics.txt")
#First thing we'll do is make a copy of the comics file and put in new folder called 'Home'.
#To do that, you'll want to use a copying method called cp on a variable called FileUtils.
FileUtils.cp('/comics.txt', '/Home/comics.txt')
# check home
Dir["/Home/*.txt"]
# "a" means append mode
# This will allow us to put new stuff at the end of the file.
File.open("/Home/comics.txt", "a") do |f|
# .. means ruby is waiting for you to finish the code
# Rubyists will use a do...end setup when the block goes on for many lines.
# do - end
File.open("/Home/comics.txt", "a") do |f|
f << "Cat and Girl: http://catandgirl.com/"
end
# read with the new comic file
print File.read("/Home/comics.txt")
# check time when I change file
File.mtime("/Home/comics.txt")
#exact hour
File.mtime("/Home/comics.txt").hour
#Files. -- Lots of methods exist for editing files and looking around in directories.
#Arguments. -- Arguments are a list of things sent into a method, separated by commas.
#Block Changes. -- You can use do and end as another way to make a code block.
# building your own methods!
def load_comics( path )
# you used def, followed by the name of the method. Next came
# a list of arguments which the method will need in order to work when you need it
def load_comics( path )
comics = {}
File.foreach(path) do |line|
name, url = line.split(': ')
comics[name] = url.strip
end
comics
end
#then
comics = load_comics('/comics.txt')
# load_comics method
# You're passing in the path variable as an argument, and you're getting back the comics variable just before the end of the method. Ruby looks for something to return just before a method's end.
#A number of methods were used to get the entire job done. See if you can spot them.
#File.foreach -- This method opens a file and hands each line of the file to the block. The line variable inside the do...end block took turns with each line in the file.
#split -- A method for strings which breaks the string up into an array, removing the piece you pass in. An axe is laid on the colon and the line is chopped in half, giving us the data to be stored in url and name for each comic.
#strip -- This quickie removes extra spaces around the url. Just in case.
# popup from library
require popup
Popup.goto "http://bing.com"
Popup.make {
h1 "My Links"
link "Go to Bing", "http://bing.com"
}
# make a list with the popup library
Popup.make do
h1 "Things To Do"
list do
p "Try out Ruby"
p "Ride a tiger"
p "(down River Euphrates)"
end
end
# make a list of the links of load_comics on a table
Popup.make do
h1 "Comics on the Web"
list do
comics.each do |name, url|
link name, url
end
end
end
1.upto(100) do |i|
if i % 5 == 0 and i % 3 == 0
puts "FizzBuzz"
elsif i % 5 == 0
puts "Buzz"
elsif i % 3 == 0
puts "Fizz"
else
puts i
end
end
Ruby on Rails Iron Hack
-----
Comments
#this is the code
=begin
klgklh
=end
----
#Put strings
puts "hello"
-----
#Put number
puts 42
----
#Put multiplication
puts 6 * 7
operation return results and then it puts =>nil
7 alone return
=>
Return last thing I did
Puts output values
#The only difference is that puts inserts a new line after printing
#while print does not.
puts "I"
puts "like"
print "Cookies"
print "good"
------
Variables
You can use them to keep track of values over time
result = 2 * 7
puts result
-----
Note: Use
minute = 60
hour = 60 * minute
day = 24 * hour
puts "Seconds in a day:"
puts day
(or day also works)
-------
String interpolation
name = "Nizar"
puts "Hi #{name}" (Put value inside inside like a template)
minute = 60
hour = 60 * minute
day = 24 * hour
puts "Seconds in a #{day}"
puts day
-------
\n (is a new line)
More printing
days = "\nMon\nTue\nWed\nThur\nFriday\nSaturday\nSunday"
puts "The days of the week #{days}"
------
Multi-line string """
beginning = """
Mon
Tue
Wed
Thur
Friday
Saturday
Sunday
"""
------
#Asking Questions
#We can write programs that ask for input from the standard input
#Grab the text from the terminal input
puts "What is your name"
name = gets.chomp
puts "Hello, #{name}!"
#When we read from the standard input with gets.chomp we are receiving
#a string. If, for some reason, we want to turn it into
#a number we need to call the to_i method on that string.
to_i stand for integer (whole numbers)
puts "Give me one number"
first_number = gets.chomp.to_i
puts "Give me one number"
second_number = gets.chomp.to_i
result = first_number * second_number
puts "#{first_number} x #{second_number} = #{first_number * second_number}"
--------
Reading files
#doesn't work on repl.it - contents = 10.read("README")
contents = IO.read("humans.txt")
puts contents
file_contents = IO.read("ruby.rb")
puts "The source file contains: #{file_contents}"
-----
Writing files
puts "Your name?"
name = gets.chomp
IO.write('humans.txt', name*100)
------
#Create a new text file
somefile = File.open("sample.txt", "w")
somefile.puts "Hello file!"
somefile.close
#Repeat hi 5 times
puts "hi" = 5
------
#Function
#A function is the most basic way we have to reuse code in our programs.
#We can define and call a function as easily as:
#def defining the functions - greet name of the functions
#functions put - get
def greet(name)
puts "Hi, #{name}!"
end
greet "niazar"
greet "Priss"
greet "clara"
-----
#Function that said good thing about first and bad to second
def props_slops(name_one, name_two)
puts "Your are great #{name_one}!"
puts "Your are bad #{name_two}!"
end
props_slops ("niazar" , "Priss")
-------
#Gets some input from person chomp
puts "Who is cool"
good_person = gets.chomp
puts "Who is bad"
bad_person = gets.chomp
props_slops good_person , bad_person
--------
Return Values
#Function returns values - variables have values
#square al cuadrado 8*8 = 64
def square (number)
number * number
end
#call the function
puts square(8)
def multiply(a, b)
return a * b
end
puts multiply(6,7)
puts square (8)
puts(square(22))
puts(square(1))
puts(multiply(3,2))
puts(multiply(10,3))
#calling the function and saving the values on variables
six_times_seven = multiply(6,7)
seven_square = square(7)
puts six_times_seven
puts seven_square
#storing new values - overriding
puts_value = puts 'test'
puts_value
------------
returning multiple values
minute = 60
hour = 60 * minute
day = 24 * hour
def time_in_days(days)
hours = 24 * days
minutes = 60 * hours
seconds = 60 minutes
return hours, minutes, seconds
end
hours, minutes, seconds = time_in_days()
puts "Threre are #{hours} in 3 days"
puts "Threre are #{minutes} in 3 days"
puts "Threre are #{seconds} in 3 days"
#When thinking about function return values, think of math operations.
#Math operations like addition have a result, a value that is obtained from the operation.
#Functions can also have a result value
# Addition returns the sum of the two numbers
puts 10 + 13
# Similarly, a function can return a result of a custom operation.
# Take a string's reverse function, for example:
puts "desserts".reverse
#Another cool thing you can do in Ruby that is not as easy to do in
#other languages is returning more than one value from a function call:
def power_formula(base_chemical)
sugar = base_chemical * 500
spice = sugar / 1000
everything_nice = sugar / 100
return sugar, spice, everything_nice
end
chemical_x = 10000
blossom, buttercup, bubbles = power_formula(chemical_x)
puts "Using the value #{chemical_x} as our base chemical"
puts "We get values of #{blossom} for blossom, #{buttercup} for buttercup, and #{bubbles} for bubbles."
--------
Comparison Logic
puts 12 == 1
puts 3 < 4
puts 12 >= 12
puts true && true
puts false && true
puts true || false
puts false || false
#with &&
#If one is false is going to be false - both have to be true
#with ||
#is different
---------
Question when user enter input
Is empty?
is more than 10 character?
--------
Program making decisions
puts "What's your name?"
name = gets.chomp
if name == ""
puts "Come on, person! Don't be shy!"
else
puts "Hello, #{name}!"
end
-----------
Conditionals
f name == ""
puts "Come on, person! Don't be shy!"
else
puts "Hello, #{name}!"
--------
else if
puts "What's your favorite animal?"
animal = gets.chomp
if animal == "porcupine"
puts "Gross!"
elseif animal == "hippo"
puts "Great!"
else
puts "I guess #{animal}s are alright."
end
-------
#Array - Looping arrays
#In our programs we will have to deal with structured lists of data.
#For that in Ruby we use the Array class. To create an array we do the following:
numbers = [ "One", 2, "Three" ]
puts numbers
#In an Array as you can see we can store any kind of value.
numbers = [ "One", 2, "Three" ]
#We can use for to iterate the collection:
for element in numbers
puts "-> #{element}"
end
#This approach is not used too much. It is much more common to see:
numbers.each do |element|
puts "--> #{element}"
end
#To add elements we can use the shovel operator << or push function.
#To remove elements we can, for example, use the delete_at function.
my_array = [ ]
my_array << "A"
my_array.push "B"
my_array.push "C"
my_array.delete_at 2
puts my_array
----
#Hashes
A Hash is an associative array. Whereas elements in an array have an order or number
associated to them, elements in a hash have a name associated to them.
It's basically like a dictionary. You can lookup values by its name or key.
my_hash = {}
my_hash["AST"] = "Asturias"
my_hash[2] = "Galicia"
puts my_hash["AST"]
puts my_hash[2]
puts my_hash
--------
#While
The while is a construct that runs a chunk of code until a condition is false.
string = ""
# While the string's length is less than 10
while string.size < 10
# Add an 'a'
string = string + 'a'
end
puts "The final string is #{string}"
---------
#Loop keep going until the condition is true
reprompt
puts "What's your name?"
name = gets.chomp
while name ==""
puts " Come tell my your name"
name = gets.chomp
end
puts "Hello, #{name}!"
-----------
以上是关于ruby Ruby基础知识的主要内容,如果未能解决你的问题,请参考以下文章