Вы находитесь на странице: 1из 5

Ruby on Rails Simple Examples & StringsLearn More

Our new digital reading service puts all your favorite documents, news, blogs, friend recommendations and more at arms reach, anytime and anywhere. Learn More Scribd Upload a Document Search Documents Explore DocumentsBooks - FictionBooks - Non-fictionHealth & MedicineBrochures/CatalogsGovernment DocsHow-To Guides/ManualsMagazines/NewspapersRecipes/MenusSchool Work+ all categoriesFeaturedRecentPeopleAuthorsStudentsResearchersPublishersGovernment & NonprofitsBusinessesMusiciansArtists & DesignersTeachers+ all categoriesMost FollowedPopulararjangi AccountHomeMy DocumentsMy CollectionsMy ShelfView Public ProfileMessagesNotificationsSettingsHelpLog Out 1First Page Previous Page Next Page / 5Sections not available Zoom Out Zoom In Fullscreen Exit FullscreenSelect View Mode View ModeSlideshowScroll Readcast Add a Comment Embed & Share Reading should be social! Post a message on your social networks to let others know what you're reading. Select the sites below and start sharing.Link accountLink accountReadcast this DocumentReadcast Complete!Click 'send' to Readcast!edit preferencesSet your preferences for next time...Choose 'auto' to readcast without being prompted.arjangiLink accountLink accountAdvancedCancel Share & EmbedAdd to Collections Download this Document for FreeAuto-hide: on Ruby on Rails : Strings Today we will look into few examples and introduce on strings with working examples. Say we start on simple math factorial function The mathematical definition ofn factorial is: n! = 1 (when n==0) = n * (n-1)! (otherwise) In ruby, this can be written as: def factorial(n) if n == 0 1 else n * factorial(n-1) end end You may notice the repeated occurrence ofend. (Note: the syntax of ruby more closely mimics that of a language named Eiffel.) You may also notice the lack of areturn statement. It is not needed because a ruby function returns the last thing that was evaluated in it. Though use of areturn statement is permissible but it is not necessary here. Let's try out our factorial function. Adding one line of code gives us a working program: # Program to calculate the factorial of a number # Save this as factorial.rb def factorial(n) if n == 0 1 else n * factorial(n-1) end end print factorial(ARGV[0].to_i), "\n" ARGV is an array which contains the command line arguments, and to_i converts a character string to an integer. 1 Prepared By: Sumanth Krishna. A Ruby on Rails : Strings Experiment: What happens if I pass string as argument instead of integer? At the line 12, replace the double quote with single quote and see what

happens?(It will be discussed in next page) 2 Prepared By: Sumanth Krishna. A Ruby on Rails : Strings AString object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created usingString::new or as literals. Because of aliasing issues, users of strings should be aware of the methods that modify the contents of aString object. Methods with names ending in ``! modify their receiver. Methods without a ``! return a newString. Ruby deals with strings as well as numerical data. A string may be double-quoted ("...") or single-quoted ( ... ). A double-quoted string allows character escapes by a leading backslash, and the evaluation of embedded expressions using#{}. A single-quoted string does not do this interpreting; what you see is what you get. Examples: If you had done the above mentioned experiments, it is easy to understand the above two points. The difference between the double and single quotes around a string. There are plenty of methods that ruby offers, they come very handy! capitalize: str.capitalize => new_str This method turns the first letter of the string to upper case. "hello".capitalize #=> "Hello" Ruby chomp: str.chomp(separator=$/) => new_str Returns a newString with the given record separator removed from the end ofstr (if present). If$/ has not been changed from the default Ruby record separator, thenchomp also removes carriage return characters (that is it will remove\n,\r, and\r\n). "ruby\r\n".chop #=> "string" "ruby\n\r".chop #=> "string\n" 3 Prepared By: Sumanth Krishna. A Ruby on Rails : Strings In Ruby, strings aremutable. They can expand as needed, without using much time and memory. Ruby stores a string as a sequence of bytes. insert: str.insert(index, other_str) => str Insertsother_str before the character at the givenindex, modifyingstr. Negative indices count from the end of the string, and insertafter the given character. The intent is insert aString so that it starts at the given index. "abcd".insert(0, X ) #=> "Xabcd" "abcd".insert(3, X ) #=> "abcXd" length: str.length => integer Returns the length ofstr. "ruby". length #=> 4 "ruby on rails". length #=> 13 ljust: str.ljust(integer, padstr= ) => new_str Ifint eger is greater than the length ofstr, returns a newString of lengthint eger withstr left justified and padded withpadstr; otherwise, returnsstr. "hello".ljust(4) #=> "hello" "ruby".ljust(20, 1234 ) #=> "ruby1234123412341234" strip: str.lstrip => new_str Returns a copy ofstr with leading whitespace removed. " hello ".lstrip #=> "hello " "hello".lstrip #=> "hello" str.rstrip => new_str Returns a copy ofstr with tailing whitespace removed. " hello ".lstrip #=> " hello" replace: str.replace(other_str) => str Replaces the contents ofstr with the corresponding values inother_str. s = "java" #=> "java" s.replace "Ruby" #=> "Ruby" reverse: str.reverse => new_str Returns a new string with the characters fromstr in reverse order. "stressed".reverse #=> "desserts" 4 Prepared By: Sumanth Krishna. A Ruby on Rails : Strings Methods with names ending in ``! modify their receiver. capitalize!: str.capitalize! => str or nil Modifiesstr by converting the first character to uppercase and the remainder to lowercase. Returnsnil if no changes are made. a = "hello" a.capitalize! #=> "Hello" a #=> "Hello" a.capitalize! #=> nil Following is the list of methods that ruby supports for the String Class. Experiment: % , *, +, <<, <=>, == , =~, [], []= , block_scanf, capitalize , casecmp, center, chomp, chop, concat, count, crypt, delete, downcase, dump, each, each_byte, each_char, each_line, hash , hex, index, initialize_copy, end_regexp, gsub, insert, inspect, intern, issjis,

isutf8, jcount, jlength, jsize, kconv, length, ljust, lstrip , iseuc, replace, reverse, Oct, quote , match , New, next, rindex, rjust, rstrip, scan, scanf, size, slice, split, squeeze, squeeze, strip, sub, sum, swapcase, unpack, upcase, upto, yaml_new chomp!, capitalize!, chop!,delete!, downcase!, gsub!, lstrip!, next!, reverse!, rstrip!, slice!, upcase!, empty?, eql?, include?, is_binary_data?, is_complex_yaml?, mbchar?, squeeze!, squeeze!, strip!, sub!, succ, succ!, swapcase!, to_f, to_i, to_s, to_str, to_sym, to_yaml toeuc tojis tosjis toutf16 toutf8 tr tr, tr!, tr!, tr_s, tr_s!, References: Ruby String Class: http://ruby-doc.org/core/classes/String.html 5 Prepared By: Sumanth Krishna. A Ruby on Rails Simple Examples & Strings Download this Document for FreePrintMobileCollectionsReport DocumentReport this document?Please tell us reason(s) for reporting this document Spam or junk Porn adult content Hateful or offensiveIf you are the copyright owner of this document and want to report it, please follow these directions to submit a copyright infringement notice.Report Cancel This is a private document. Info and Rating Reads:62,922Uploaded:12/18/2007Category:Uncategorized.Rated:4 Ratings()Copyright:Attribution Non-commercialThis document starts with simple math factorial function example and details the Ruby String Class with examples... ScienceTechnologyrailsrubyrubyonrailsrorstringclassrubystringsTechnology-General ScienceTechnologyrailsrubyrubyonrailsrorstringclassrubystringsTechnology-General (fewer) Sumanth KrishnaShare & Embed Related Documents PreviousNext p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p. p.

p. p. p. p. p. p. p. p. p. p. p. p. p. p.More from this user PreviousNext 3 p. 24 p. 1 p. 27 p. 14 p. 56 p. 2 p. 5 p. 10 p. 31 p. 0 p. 10 p. 20 p. 11 p. 1 p. 5 p. 3 p. 4 p. 2 p. 6 p. 14 p. 2 p. 2 p. 9 p. 42 p.Recent Readcasters Add a Comment SubmitCharacters: 400 Print this documentHigh QualityOpen the downloaded document, and select print from the file menu (PDF reader required).Download and Print Add this document to your CollectionsThis is a private document, so it may only be added to private collections.+ Create a New CollectionName:Description:Collection Type:public - locked public - moderated privatepublic locked: only you can add to this collection, but others can view it public moderated: others can add to this collection, but you approve or reject additions private: only you can add to this collection, and only you will be able to view itSave collectionCancelFinished? Back to Document Upload a Document Search Documents Follow Us!scribd.com/scribdtwitter.com/scribdfacebook.com/scribdAboutPressBlogPartner

sScribd 101Web StuffScribd StoreSupportFAQDevelopers / APIJobsTermsCopyrightPrivacyCopyright 2011 Scribd Inc.Language:EnglishChoose the language in which you want to experience Scribd:EnglishEspaolPortugus (Brasil) Download this document pdf doc txt 918737-Ruby-on-Rails-Simple-E....pdf - 147.6 KBDownload NowReadcast: The Scribd Archive This document was uploaded by someone just like you and is now part of The Scribd Archive*. Give back to the community and gain 24 hours of download access by uploading something of your own.Do you understand the Scribd Terms of Service and Copyright Policy, and confirm that your uploading of this material complies with those policies and does not violate anyone s rights?Queued: Uploading: You have uploaded: Upload failed: Document URL: This document is: PrivateThis document is: PublicCancel Upload Make it easier to find your new document!Title: Category: Presentations Choose a Category Art & Design Brochures/Catalogs Business/Law Government Docs How-To Guides/Manuals Recipes/Menus Research School Work Spreadsheets Choose a Category Business/Law How-To Guides/Manuals Research School Work Choose a Category Art & Design Comics Reviews (NEW) Op-Ed (NEW) Letters to Our Leaders (NEW) Books - Fiction Books - Non-fiction Brochures/Catalogs Business/Law Creative Writing Government Docs How-To Guides/Manuals Magazines/Newspapers Puzzles/Games Recipes/Menus Research Resumes/CVs School Work Speeches Please select a top level category first Automobiles Crafts Gadgets Scrapbooking Court Filings Finance Marketing Real Estate Taxes & Accounting Technology Biography Health & Lifestyle History Philosophy Politics Psychology Religion & Spirituality Self-Help Travel Calendars Crosswords Word Search Essays & Theses Homework Study Guides, Notes, & Quizzes Book Film Music Art Essays Fan Fiction Humor Memoirs Novels Poetry Screenplays & Plays Short Stories Chick Lit Children s Literature Romance Science Fiction & Fantasy Thrillers Young Adult Bills Forms Letters Public Notices Maps Origami Photography Posters Arts & Architecture Business & Economics Genealogy Health & Medicine History Internet & Technology Law Literature Math & Engineering Science Tags: (separate with commas) Description: Save Subscribe to The Scribd Archive and download as many documents as you d like.Monthly SubscriptionMost Popular$9/mo.1 Day Pass$51 Year Pass$59Choose payment optionPay with Credit CardPay with PayPal or Credit* The Scribd Archive is a collection of millions of documents, including research reports, best-selling books, news source materials, and more. Read the Scribd Archive FAQ for more information.Thanks for uploading! Download this document as pdf doc txt 918737-Ruby-on-Rails-Simple-E....pdf - 147.6 KBDownload Now

Вам также может понравиться