Try Ruby in browser

来源:百度文库 编辑:神马文学网 时间:2024/04/19 20:44:21
http://tryruby.hobix.com/
Try Ruby
Interactive ruby ready.
>> ‘a‘.upcase
=> "A"
>> ‘a  ‘.strip
=> "a"
>> ‘a‘.upcase
=> "A"
>> ‘a  ‘.strip
=> "a"
>> ‘a‘.strip!
=> nil
>>
>>
>>
Got 15 minutes? Give Ruby a shot right now!
This tutorial is only partway complete and is still very experimental! If nothing works, uh... come back in a few days? Thankyou!
Ruby is a programming language from Japan (available atruby-lang.org) which is revolutionizing the web. The beauty of Ruby is found in its balance between simplicity and power.
Try out Ruby code in the prompt above. In addition to Ruby‘s builtin methods, the following commands are available:
help Start the 15 minute interactive tutorial. Trust me, it‘s very basic! clear Clear screen. Useful if your browser starts slowing down. Your command history will be remembered. time A stopwatch. Prints the time your session has been open.
If you happen to leave or refresh the page, your session will still be here for unless it is left inactive for an hour two minutes (due to recent load.)
Using the Prompt
The blue window above is a Ruby prompt. Type a line of Ruby code, hit Enter and watch it run!
For example, try typing some math. Like: 2 + 6
\d+
Numbers & Math
Good! You did a bit of math. See how the answer popped out?
Ruby recognizes numbers and mathematic symbols. You could try some other math like:
4 * 10 5 - 12 40 / 4
Sure, computers are handy and fast for math. Let‘s move on. Want to see your name reversed? Type your first name in quotes like this: "Jimmy"
"(\w+)"
Say Your Name Backwards
Perfect, you‘ve formed a string from the letters of your name. A string is a set of characters the computer can process.
Imagine the letters are on a string of laundry line and the quotes are clothespins holding the ends. The quotes mark the beginning and end.
To reverse your name, type: "Jimmy".reverse (Don‘t forget the dot!)
"(\w+)"
Counting the Letters
You have used the reverse method on your name! By enclosing your name in quotes, you made a string. Then you called the reverse method, which works on strings to flip all the letters backwards.
Now, let‘s see how many letters are in your name: "Jimmy".length
\d+
On Repeat
Now, I‘m sure by now you‘re wondering what any of this is good for. Well, I‘m sure you‘ve been to a website that screamed, Hey, your password is too short! See, some programs use this simple code.
Watch this. Let‘s multiply your name by 5. "Jimmy" * 5
"(\w+)"
Hey, Summary #1 Already
Let‘s look at what you‘ve learned what you‘ve learned in the first minute.
The prompt. Typing code into the green prompt gives you an answer from a red prompt. All code gives an answer. Numbers and strings are Ruby‘s math and text objects. Methods. You‘ve used English-language methods like reverse and symbolic methods like * (the multiplication method.) Methods are action!
This is the essence of your learning. Taking simple things, toying with them and turning them into new things. Feeling comfortable yet? I promise you are.
Okay, let‘s do something uncomfortable. Try reversing a number: 40.reverse
NoMethodError: undefined method `reverse‘ for (\d+):Fixnum
Stop, You‘re Barking Mad!
You can‘t reverse the number fourty. I guess you can hold your monitor up to the mirror, but reversing a number just doesn‘t make sense. Ruby has tossed an error message. Ruby is telling you there is no method reverse for numbers.
Maybe if you turn it into a string: 40.to_s.reverse.
\"(\d+)\"
Boys are Different From Girls
And numbers are different from strings. While you can use methods on any object in Ruby, some methods only work on certain types of things. But you can always convert between different types using Ruby‘s "to" methods.
to_s converts things to strings. to_i converts things to integers (numbers.) to_a converts things to arrays.
What are arrays?! They are lists. Like this: [].
\[\]
Standing in Line
Great, that‘s an empty list. Lists store things in order. Like standing in line for popcorn. You are behind someone and you wouldn‘t dream of pushing them aside, right? And the guy behind you, you‘ve got a close eye on him, right?
Here‘s a list for you. Lottery numbers: [12, 47, 35].
\[(\d+(, )?){2,}\]
One Raises Its Hand
A list of lottery numbers. Which one is the highest?
Try: [12, 47, 35].max.
(\d+)
Tucking a List Away
Good, good. But it‘s annoying to have to retype that list, isn‘t it?
Let‘s save our numbers inside a ticket like so: ticket = [12, 47, 35]
\[(\d+(, )?){2,}\]
Now Type Ticket
Now, type: ticket
\[(\d+(, )?){2,}\]
Summary #2 is Upon Us
Fantastic! You‘ve hung on to your lotto numbers, tucking them away inside a variable called ticket. Look how your second minute went:
Errors. If you try to reverse a number or do anything fishy, Ruby will skip the prompt and tell you so. Arrays are lists for storing things in order. Variables save a thing and give it a name. You used the equals sign to do this.
Like: ticket = [14, 37, 18].
In all there are ten lessons. You are two-tenths of the way there! This is simple stuff, don‘t you think? Good stuff up ahead.
Let‘s put your lotto numbers in order, how about? Use: ticket.sort!
\[(\d+(, )?){2,}\]
Changed! For good!
You had a list. You sorted the list. The ticket variable is now changed.
Did you notice that the sort! method has a big, bright exclamation at the end? A lot of times Ruby methods shout like that if they alter the variable for good. It‘s nothin special, just a mark.
Let‘s change directions for a moment. I‘ve stuffed a bit of poetry for you in a certain variable. Take a look. Type: print poem poem = "My toast has flown from my hand\nAnd my toast has gone to the moon.\nBut when I saw it on television,\nPlanting our flag on Halley‘s comet,\nMore still did I want to eat it.\n"
My toast (.+)
Sadly, You Hate Toast Poetry
Look, it‘s okay. You don‘t have to like it. Hack it up, be my guest.
Instead of toast, go for a melon or something. Try this: poem[‘toast‘] = ‘honeydew‘
And then type print poem by itself to see the new poem.
My honey(.+)
Ready, Aim
The square brackets you just used are very common in Ruby. Remember, you typed: poem[‘toast‘] = ‘honeydew‘. That box with the word toast has a square bracket on each side, see?
The two brackets are like sights used to line up a target. Exactly. These brackets mean, "I am looking for ____." Ready, aim. Here you‘re looking for toast and swapping it out with fruit.
Here‘s a question: what happens when we reverse this whole poem? poem.reverse "\\n.ti tae ot (.+)"
Too Much Reversal
Okay, sure. So the whole poem‘s been turned backwards, letter-by-letter. I really want to just reverse the lines, though. Move the last line up to first and the first line down to last. Backwards, but not that backwards.
Here‘s how: poem.to_a.reverse
\["More still did I(.+)"\]
Ringlets of Chained Methods
So what do you see? What happened there? You typed poem.to_a.reverse and what happened?
Two things happened. You turned the poem into a list using to_a. (To array.) When Ruby turns a string into an array, its breaks the whole thing up at each line break. So you end up getting each line of the poem.
Then, you reversed that list. You had each line. You reversed them. That‘s it.
Let‘s tack one more method on the end there: print poem.to_a.reverse.join More still did I(.+)
Of All the Summaries, #3 is Here Now
Good show, my friend! The join method took that list of reversed lines and put them together into a string. (Sure, you could have also just used to_s.)
Review time.
Exclamations. Methods may have exclamations (and also question marks) in their name. No big deal. Try: poem.include? "my hand" Square brackets. Target and find things. Search and replace. Chaining methods lets you get a lot more done. Break up a poem, reverse it, reassemble it: poem.to_a.reverse.join
At this point, you may want to tinker with the poem a bit more. A complete list of all the String methods ishere. Go ahead and try a few (such as poem.downcase or poem.delete.)
When you‘re ready to move on, type: books = {}
\{\}
A Wee Blank Book
You‘ve made an empty hash. (Also known as: an empty dictionary.
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. :abyssmal → 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
:\w+
More Bite-Size Reviews
Keep going, fill it up with reviews. And, if you want to see the whole list, just type: books
Again, the ratings are: :splendid, :quite_good, :mediocre, :quite_not_good, and :abyssmal.
These ratings are not strings. When you place a colon in front of a simple word, you get a symbol. Symbols are cheaper than strings (in terms of computer memory.) If you use a word over and over in your program, use a symbol. Rather than having thousands of copies of that word in memory, the computer will store the symbol only once.
Once you‘ve got three or four books in there, type: books.length.
[3-9]
Wait, Did I Like Gravity‘s Rainbow?
See, the length method works on strings, list and hashes. One great thing about Ruby is that names are often reused, which means fewer names you need to remember.
If you‘d like to look up one of your old reviews, again put the title in the square. But leave off the equals.
Just like this: books["Gravity‘s Rainbow"]
:\w+
Hashes as Pairs
Keep in mind that hashes won‘t keep things in order. That‘s not their job. It‘ll just pair up two things: a key and a value. In your reviews, the key is the book‘s title and the value is the rating.
If you want to just see the titles of the books you‘ve reviewed: books.keys
\[".*"\]
Are You Harsh?
So are you giving out harsh, unfair reviews? Let‘s keep score with this hash:
ratings = Hash.new {0}
Then, okay, now let‘s count up your reviews. Just stay with me. Type:
books.values.each { |rate| ratings[rate] += 1 }
\[:.+\]
A Tally
Great, wow! You‘ve made a scorecard of your ratings. Type ratings to see the count. This new hash shows a rating and then the number of times you‘ve given that rating.
One of the amazing new things we‘ve just added is a block. We‘re going to explore these more in the next summary. But, basically, a block is a bit of Ruby code surrounded by curly braces.
Let‘s try another block: 5.times { print "Odelay!" }
Odelay!Od.*
Now Arriving at Summary #4
Blocks are always attached to methods. Like the times method, which takes the block and runs the code over and over. (In this case: five times.)
This last lesson was a bit longer. You‘ve probably used up three minutes learning about:
Hashes. The little dictionary with the curly pages: {}. Symbols. Tiny, efficient code words with a colon: :splendid. Blocks. Chunks of code which can be tacked on to many methods. Here‘s the code you used to build a scorecard: books.each { |title, rate| ratings[rate] += 1 }.
Well, this is as far as the tutorial goes for now. Indeed, I‘m only halfway done. Come back in a few days and I‘ll have more, surely.
NO
No Further
For now, this tutorial goes no further.
This service is brought to you bywhy the lucky stiff. Please contact me using the email address at that link. And if you‘d like to dig into Ruby further, I‘m working on a free guide:Why‘s (Poignant) Guide to Ruby.