Powróćmy do prostych przykładów

Teraz weźmy części kodu z kilku naszych poprzednich przykładowych programów.

Następujący kod pojawił się w rozdziale "proste przykłady".

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

puts fact(ARGV[0].to_i)

Ponieważ jest to pierwsze objaśnienie, zbadamy każdą linię osobno.

Silnie

def fact(n)

W pierwszej linii, def jest instrukcją służącą do definiowania funkcji (lub bardziej precyzyjnie, metodą, będziemy więcej rozmawiać o tej metodzie w późniejszym rozdziale). Tutaj, to określa że funkcja fact bierze pojedynczy argument, odnoszący się do n.

if n == 0

Instrukcja if służy do sprawdzania warunku. Kiedy warunek jest spełniony, następny fragment kodu jest wykonywany; w przeciwnym razie, cokolwiek jest po else zostanie wykonane.

1

Wartość z if'a to 1, jeżeli warunek jest spełniony.

else

Jeśli warunek nie jest spełniony, kod stąd do end jest wykonywany.

n * fact(n-1)

Jeżeli warunek nie został spełniony, wartość z if'a zostanie wynikiem n pomnożonym przez fact(n-1).

end

Pierwszy end zamyka blok if

end

Drugi end zamyka blok def.

puts fact(ARGV[0].to_i)

To wywołuje naszą funkcję fact() z wartością określoną w wierszu poleceń oraz wypisuje jej wynik.

ARGV jest tablicą, która zawiera argumenty z wiersza poleceń. Tablica ARGV zawiera łańcuchy znaków (stringi), więc musimy skonwertować je na liczby całkowite przez to_i. Ruby nie konwertuje łańcuchów do liczb całkowitych automatycznie tak jak perl.

Co by się stało, gdybyśmy podali temu programowi liczbę ujemną? Czy widzisz problem? Czy możesz to naprawić?

Łańcuchy znaków

Następnie zbadamy program łamigłówkę z artykułu o łańcuchach znaków. Ten przykład jest nieco dłuższy, więc ponumerujemy linie dla odniesień.

slowa = ['pietruszka', 'seler', 'marchewka']
sekret = slowa[rand(3)]

print "trafienie? "
while trafienie = STDIN.gets
  trafienie.chop!
  if trafienie == sekret
    puts "Wygrałeś!"
    break
  else
    puts "Przykro mi, przegrałeś."
  end
  print "trafienie? "
end
puts "To słowo to "+sekret+"."

W tym programie jest nowa struktura kontroli, while, jest użyte. Kod pomiędzy while a jego zakończeniem end będzie wykonywany tak długo jak pewien określony warunek pozostanie prawdą. W tym przypadku, guess=STDIN.gets jest zarówno aktywną instrukcją (pobierającą linię wejściową od użytkownika i zachowującą ją jako odp), a warunek (jeśli nie ma wejścia, odp, które reprezentuje wartość całego trafienie=STDIN.gets wyrażenie ma wartość nil, która spowoduje przerwanie pętli while).

STDIN jest obiektem standardowego wejścia. Zwykle trafienie=gets robi to samo, co trafienie=STDIN.gets.

rand(3) w linii 2 zwraca losową liczbę w przedziale od 0 do 2. Ta losowa liczba jest użyta do wyciągnięcia jednego z członków tablicy slowa.

W linii 5 czytamy jedną linię ze standardowego wejścia przez metodę STDIN.gets. Jeśli EOF (koniec pliku) występuje podczas pobierania linii, gets zwróci nil. Tak więc kod związany z tym while będzie powtarzany dopóki nie zobaczy ^D (spróbuj ^Z lub F6 pod DOS/Windows), co oznacza koniec wejścia.

guess.chop! w linii 6 usuwa ostatni znak z trafienie; W tym przypadku będzie to zawsze znak nowej linii, dostaje ten znak by odzwierciedlić naciśnięcie klawisza Return (enter), ale nie jesteśmy tym zainteresowani.

W linii 15 drukujemy tajne słowo. Napisaliśmy to jako instrukcję puts (put string) z dwoma argumentami, które są drukowane jeden po drugim; ale byłoby to równie efektywne, gdyby to było zrobione z jednym argumentem, zapisując sekret jako #{sekret} by było jasne, że jest to zmienna do przetworzenia, a nie dosłowne słowo drukowane:

puts "To słowo to #{sekret}."

Wielu programistów uważa, że ​​jest to czytelniejszy sposób formułowania wyjścia; buduje to pojedynczy łańcuch i przedstawia go jako pojedynczy argument dla puts.

Ponadto, jesteśmy już przyzwyczajeni do idei użycia puts dla standardowego wyjścia skryptu, ale ten skrypt wykorzystuje natomiast print w liniach 4 i 13. Nie są one zupełnie takie same. Wyjście print zwraca dokładnie to, co jest podane; puts zapewnia również znak końca linii. Używanie print w liniach 4 i 13 pozostawia kursor obok tego co było właśnie drukowane, zamiast przenosić go na początek następnego wiersza. Tworzy to rozpoznawalny znak zachęty do wprowadzania danych przez użytkownika. Na ogół, poniższe cztery połączenia wyjścia są równoważne:

# nowa linia jest dodawana przez puts, jeżeli już jej tutaj nie ma:
puts  "Żona Darwina, Esmeralda, zmarła w przypływie pingwinów."

# nowa linia musi być jawnie dodany do polecenia print:
print "Żona Darwina, Esmeralda, zmarła w przypływie pingwinów.\n"

# możesz konkatenować wyjście stosując +:
print 'Żona Darwina, Esmeralda, zmarła w przypływie pingwinów.'+"\n"

# lub konkatenować przez podawanie więcej niż jednego łańcucha:
print 'Żona Darwina, Esmeralda, zmarła w przypływie pingwinów.', "\n"

Jeden możliwy haczyk: czasami okno tekstowe jest zaprogramowane tak, aby bufor wyjściowy przez wzgląd na szybkość, zbiera poszczególne znaki i wyświetla je tylko wtedy, gdy podany jest znak nowej linii. Więc jeśli skrypt zgadywanki nie pokazuje wierszy aż użytkownik dostarcza odpowiedzi, buforowanie jest prawdopodobnym winowajcą. Aby upewnić się, że tak się nie stanie, można opróżnić(flush) wyjście zaraz po wydrukowaniu wiersza. To mówi standardowemu wyjściu urządzenia (obiekt nazwany STDOUT), "nie czekaj; wyświetl co masz w buforze teraz."

04 print "trafienie? "; STDOUT.flush
  ...
13 print "trafienie? "; STDOUT.flush

A w rzeczywistości, byliśmy bardziej ostrożni z tym w następnym scenariuszu.

Wyrażenia regularne

W końcu zbadamy program z rozdziału o wyrażeniach regularnych.

st = "\033[7m"
en = "\033[m"

puts "Enter an empty string at any time to exit."

while true
  print "str> "; STDOUT.flush; str=gets.chop
  break if str.empty?
  print "pat> "; STDOUT.flush; pat=gets.chop
  break if pat.empty?
  re = Regexp.new(pat)
  puts str.gsub(re, "#{st}\\&#{en}")
end

W linii 6, warunek pętli while jest zawsze prawdą, co w efekcie daje nam nieskończoną pętlę. Jednak umieszczamy instrukcję break w 8 i 10 linii by uciec z pętli. Te dwa break'i są także przykładem "modyfikatorów if." Modyfikator if wykonuje instrukcje po swojej lewej stronie wtedy i tylko wtedy, gdy określony warunek jest spełniony. Konstrukcja ta jest niezwykła, gdyż działa logicznie od prawej do lewej, ale jest tak dlatego, ponieważ dla wielu ludzi jest to podobny naturalny wzór w mowie, który to naśladuje. Ma ono też zaletę, zwięzłość, gdyż nie wymaga instrukcji end do powiedzenia interpreterowi ile z następującego kodu ma być warunkowa. Modyfikator if jest tradycyjnie stosowany w sytuacjach, gdzie instrukcja i warunek są wystarczająco krótkie by zmieścić się razem w jednej linii skryptu.

Zauważ różnicę w interfejsie użytkownika w porównaniu do skryptu ciągu-zgadywania. Ten pozwala użytkownikowi zakończyć naciskając klawisz Enter w pustym wierszu. Testujemy dla pustego ciągu wejściowego, nie dla jego nieistnienia.

W liniach 7 i 9 mamy "nie-destruktywny" chop; znowu mamy pozbyć się niechcianego znaku nowej linii zawsze otrzymywanego od gets. Dodaj wykrzyknik i mamy "destruktywny" chop. Co za różnica? W ruby, mamy umownie dołączony '!' lub '?' na końcu nazw pewnych metod. Wykrzyknik (!, czasami głośny tak jak "huk!") oznacza coś potencjalnie destrukcyjnego, to znaczy, że coś może zmienić wartość tego, co to dotyka. chop! ma bezpośredni wpływ na łańcuch, ale chop daje Tobie obciętą kopię bez psucia oryginału. Oto ilustracja tej różnicy.

ruby> s1 = "forth"
  "forth"
ruby> s1.chop!       # This changes s1.
  "fort"
ruby> s2 = s1.chop   # This puts a changed copy in s2,
  "for"
ruby> s1             # ... without disturbing s1.
  "fort"

Będziesz też czasem widzieć chomp i chomp! używany. Są bardziej selektywne: koniec łańcucha jest wyłączany tylko wtedy, gdy tworzona jest nowa linia. Więc dla przykładu, "XYZ".chomp! nic nie robi. Jeśli potrzebujesz zapamiętać różnicę tego trick'u, pomyśl o osobie albo zwierzęciu próbującym coś przed podjęciem decyzji o wzięciu kęsa, w przeciwieństwie do siekania siekierą na oślep.

Inna konwencja nazywania metod pojawia się w liniach 8 i 10. Znak zapytania (?, czasem wyraźnie głośne jak "heh?") wskazuje na "twierdzenie" metodę, jedną która może zwrócić zarówno prawę czy fałsz.

Linia 11 tworzy wyrażenie regularne obiektu z łańcucha dostarczanego przez użytkownika. Prawdziwa praca jest ostatecznie gotowa w linii 12, która używa gsub(od ang. globally substitute) do globalnego zastąpienia każdego porównania tego wyrażenia z samym sobą, ale otoczonego przez znaczniki ANSI; Ta sama linia wyświetla również wyniki.

Moglibyśmy podzielić linię 12 na osobne linie, tak jak poniżej:

highlighted = str.gsub(re,"#{st}\\&#{en}")
puts highlighted

lub w "destrukcyjnym" stylu:

str.gsub!(re,"#{st}\\&#{en}")
puts str

Spójrz ponownie na ostatnią część linii 12. st i en zostały zdefiniowane w liniach 1-2 jako sekwencje ANSI które sprawiają, że kolor tekstu jest odwrócony i normalny, odpowiednio. W linii 12 są one zawarte w #{}, aby zapewnić, że są one właściwie interpretowane jako takie (i w zamian nie widzimy drukowanych nazw zmiennych). Pomiędzy nimi widzimy \\&. To jest trochę chytre. Od zastąpienia łańcucha w cudzysłowie parą backslash'y będących interpretowanych jak pojedynczy backslash; co gsub zobaczy właściwie jako \&, i że dzieje się specjalny kod, który odnosi się do tego, co pasowało do wzorca w pierwszej kolejności. Tak więc nowy łańcuch, gdy będzie wyświetlony będzie wyglądał tak jak pierwszy z wyjątkiem tego, że te fragmenty które pasują do wzorca będą wyświetlone w odwróconych kolorach.

KIRAcags
To determine internal swelling is difficult enough, therefore, consequently, they influence the body for a long time, which threatens the normal fetus. Fluids are dangerous because they break blood circulation. Similar picture leads to worsening feeding and the breath baby, formed hypoxia. Fighting such a pathology should be done with the help of correction feeding and special procedures so that fluid does not stay tissues. If expectant mother is resting, then under the feet better put a cushion or pillow to improve the blood circulation of tired legs. Prohibited long time to sit or stand, as this leads to stagnation in the body. It is recommended that the knee-elbow position several times a day in order to increase blood flow. pregnancyplus.info
MirkaDuff
Peels help to eliminate from most age changes of the skin cover. operations effective at any age, shown for skin of any species. After superficial peeling disappear minor wrinkles, skin turns out smooth, smooth. Adaptation – three days. The middle peeling beautifully struggles wrinkles (expression, age, affects hardly noticeable scars, removes spots. Regeneration – 7 days. Deep peeling performing in the beauty hospitals. This is very efficient operation, although requires long term rehabilitation – up to thirty days. benefits of a chemical peel
MirkaDuff
Peels help to escape from most old amendments dermatological cover. exfoliation efficient at any time, suitable for skin of any species. After non-traumatic exfoliation disappear minor wrinkles, epidermis turns out young, without wrinkles. Adaptation – 3 days. deeper peeling well struggles wrinkles (expression, old, affects hardly noticeable scars, eliminates age spots. Regeneration – 7 days. Deep peeling conducting in the beauty medical facilities. This is very effective procedure, but requires long term regeneration – about one month. chemical peel results
KulCalt
Lump armpit brings inconvenience, pulls. to Carry trip in the hospital cannot be. Formation under the muscle cavity may become dangerous disease. But more often it is consequences frequent use antiperspirants with aluminum, non-compliance rules personal hygiene, excessive sweating. Inflammation triggers a close blouse, contaminated razor-affiliation, the infection. painless lump in armpit Discomfort under the arm, redness, lump getting hot? This is the boil that should will have to be opened, next drink antibiotics. In the first stage treat lotions, antibacterial drugs. If the process switched to second stage, shown surgical procedure.
KulCalt
Seal armpit brings discomfort, pain when moving. to Carry trip doctor should not. Formation under the muscle cavity may turn out to be cancer illness. However most often it is consequences frequent use antiperspirants with aluminum, violation rules personal hygiene, increased sweating. Redness triggers narrow blouse, contaminated razor, the virus. http://armpit.info/ Pain under the arm, redness, lump becoming hot? This is the abscess that should operated on, then take medications. first stage treat solutions, anti-inflammatory medicines. When the ailment switched to second stage, need surgery.
Cryptotext
Bitcoin normalmente relacionam-se a equipe digitais de dinheiro. Ela vive exclusivamente em formato virtual. Apesar de sua real trocados por produtos, servicos ou convencionais financas. Bitcoin unique. Ela nao ligado com as atividades dos bancos, nao tem material aparencia, e desde o inicio projecao desregulada e descentralizada. Se elementar palavras, o que e o bitcoin e digital dinheiro, que sao extraidas em digital dispositivos e giram no proprio sistema de seu leis. investir bitcoins
BTCTip
Zobacz jak zachowuje siД™ ropa na najwiД™kszej gieЕ‚dzie walutowej Forex. Analitycy Goldman Sachs pozostajД… przy swoich dotychczasowych prognozach i contacto de requisitos Gabriel Teodros habla con el artista de hip-hop, mick jenkins, sobre las piezas de un hombre de comercio etГ©reo.
TomRew
Animos Toni, y felicidades aunque sea con retraso, te explico mi caso, antes del verano me quede enganhado de la espalda y estuve unos 20 dias de baja, treasure hunt Bwl canadian historical brides dream trip north escoliosis tratamiento fisioterapeutico
Udofum
ComissГµes de admissГЈo querem saber como vocГЄ pode adicionar ao seu programa, e isso torna a marca pessoal vital. VocГЄ sabe, sem dГєvida melhor do que arthrosis
DenMow
Become a dental assistant in just 11 weeks! Our dental assistant school offers hands-on practice to gain experience! Job placement! http://bobijoel.ml/page/what-does-a-dental-hygienist-do/
DogHah
Find Dental Hygiene Programs in Florida. Get Informed on Professional Requirements, Area, Total Employed, Mean Hourly Wage, Mean Annual Salary http://drezden.pp.ua/page/boxer-dog-price-in-mumbai/
BernQuied
In this particular manner, also it burn fat rather than protein that your body requirements. You will let the body recover from the exercise stress effectively. You should definitely warm-up and funky right right down to avoid pains. http://magdalenabus.tk/page/how-to-heal-burnt-lips/
Cocoequib
The quickest and easiest way to get rid of fleas without spending much money is by giving your dog a bath with any bar of soap or dish soap. Keep in mind the reason Getting a massage while pregnant
PozziNum
Best Manchester Clubs Manchester is world famous for delivering diverse and dangerously addictive clubs to its party goers, and rightly so. With a rich and eclectic musical heritage that earns envious glares from cities the breadth of the country, Manchester is the undisputed Northern clubbing mecca. Chinese reflexology
UhaMut
(Haldol is a drug used to treat schizophrenia and Tourette’s syndrome, while Thorazine is an anti-psychotic medication used to treat schizophrenia and manic [url=http://Haloperidol.nodes.top/art/haloperidol/]Haloperidol[/url]
Noninon
Mannitol facilitates neurotrophic factor up-regulation and behavioural recovery in neonatal hypoxic-ischaemic rats with human umbilical cord blood grafts., Yasuhara T [url=https://anoxia.info/cannabis-puerto-rico-myworld-anoxic-tank-mixer]anoxic tank retention time[/url]
ScrolVab
Dolor lumbar - Importancia del mГєsculo psoas y su estiramiento - Duration: 8:47. FisioOnline 394,992 views. 8:47. Ejercicios de estiramiento de 1 minuto para ayudar a reducir el dolor de espalda [url=http://escoliosislumbar.info/the-25-best-waterproof-backpacks-of-2019-adventure]backpack straps[/url]
WINZet
Coffee causes unsightly stains that can hurt your smile. Fortunately, there are some tips you can follow to reduce stains and prevent some other issues that coffee causes. Tips to reduce coffee stains on teeth 1. Add milk. The darker the coffee is, the da [url=http://wisdomteethremoval.denta.top/art/wisdom-teeth-meaning/]Wisdom teeth meaning[/url]
DENMids
Yahoo Canada Answers Sign in Mail вљ™ Help. Account Info; Help; Send Feedback [url=http://denta.top/art/local-emergency-dentist/]Local emergency dentist[/url]
Suttital
fungal infection over face herpes what oral now i There’s a nutrient that experts say helps your body produce its main source of energy and impacts at least 300 enzyme systems. Rash High Fever Sore Throat For Medicine Ear Fungal Infection A trivalent flu shot made with adjuvant Stomach Flu (Gastroenteritis) antibiotics do not work on the virus that causes stomach flu. [url=http://yeastinfection.nodes.top/art/yeast-infection-on-skin/]Yeast infection on skin[/url]
EGGGuax
Providing precise dental care with a gentle touch, we strive to make every visit to our office a comfortable and stress-free experience. Whether your visit with us is for a routine checkup and cleaning, dental fillings, a root canal procedure, a cosmetic smile makeover, dental implants or emergency care, we are well prepared to serve your dental needs. [url=http://eggrolls.ml/art/pork-and-shrimp-egg-rolls/]Pork and shrimp egg rolls[/url]
AcuraPaw
Kenneth Bruce Bald (d. 1 Ağustos 1920 –ö. 17 Mart 2019), Amerikalı çizgi roman sanatçısı. [url=http://acjointarthritis.cf/art/arthritis-patient-education/]Arthritis patient education[/url]
Testaf
At Healthy and Natural World, our mission is to empower people to take control of their own health by providing comprehensive, practical and well researched information. Our articles are based on scientific evidence, written by experts and fact checked by experts. [url=http://tartaronteeth.cf/art/how-to-get-rid-of-tartar-on-teeth-without-dentist/]How to get rid of tartar on teeth without dentist[/url]
DOLIMug
Are you thinking of undergoing Breast Augmentation? Planning your recovery is an important step. Learn more about Breast Implant recovery at Panacea Plastic Surgery, serving the Atlanta and Conyers areas. [url=http://chemicalpeel.in/salon-deep-chemical-peel-before-and-after]deep chemical peel before and after[/url]
Qrlhek
In cosmetic applications, botulinum toxin (in this context also known as "botox") is considered safe and effective for reduction of facial wrinkles, especially in the uppermost third of the face. Injection of botulinum toxin into the muscles under facial wrinkles causes relaxation of those muscles, resulting in the smoothing of the overlying skin. [26] [url=http://botoxinjectionsites.cf/art/botox-chronic-migraine-injection-sites/]Botox chronic migraine injection sites[/url]
TenLext
These include Vitamins A, B6, B12, C, D, E, biotin, niacin, calcium, folic acid, iron, magnesium, zinc, and riboflavin. Dietary supplements are formulated for use at a specific dosage. You should always follow the directions for dosage to get the greatest benefit from any supplement. [url=http://biotin24.cf/art/biotin-meaning/]Biotin meaning[/url]
Bimkex
These assisted living facilities accept persons with conditions like Parkinsons, Alzheimers, and elders who need assistance/ are bedridden, but do not [url=http://gaselectricity.in/why-fleets-will-drive-adoption-of-electric]internal combustion[/url]
Yuldog
• Don’t handle the garment with your nails, jewelry or pointed objects. • Hold the garment with your fingertips. 1. While standing, put on the garment like a vest with the hooks and zipper open. Wear it as an undershirt. 2. Start to close the hooks [url=http://flakynails.cf/art/flaky-nails3/]Flaky nails[/url]
ETHLEF
Bitcoin price: Cryptocurrency expert reveals what will cause bitcoin to surpass new high Brussels backs down: Italy escapes EU budget punishment – £2.6bn fine threat scrapped Tesco warn of empty shelves as stockpiling for no deal Brexit ‘harder’ before Christmas [url=http://bitcoinfr.biz/mainstreet-bank-bancshares-reports-successful/]bitcoin price euro[/url]
CepLola
The bitcoin price has dropped by as much as 18 percent from its 2019 high of $9,090. And it could lose more value in the coming 20 days, according to an analysis provided by a cryptocurrency analyst. And it could lose more value in the coming 20 days, according to an analysis provided by a cryptocurrency analyst. [url=https://bitcoinpor.top/o-mercado-bioestimulantes-estimado-em-usd-2-00/]bitcoin market[/url]
Craftnal
top 5 mcpe servers,best mcpe servers,mcpe servers,best minecraft servers,minecraft pe servers skywars,minecraft skywars servers,servers,minecraft skywars server ip 1.8 deutsch,minecraft server [url=http://minecraft-game.ga/los-miserables-episodio-6-resumen-un-dia-mas-telly]juego de minecraft[/url]
VillaMaF
From the sociological perspective, the class structure as the basis of social inequalities is, . Classification into social classes was based on the 1988 data. [url=http://social-class.ga/art/what-is-social-class2/]What is social class[/url]
Mikocill
Scalp Problems (Skin Diseases on Head) Types and Causes There are number of different types of scalp problems that can cause a host of symptoms, such as itching, redness, lesions like pimples, flaking of the skin and hair loss. [url=http://psoriasisinchildren.ml/art/psoriasis-in-children17/]Psoriasis in children[/url]
JoniNal
26 May 2014 Faucet leaks can be troublesome as well if the water is draining down the back of the faucet, causing it to drain underneath the sink. To fix a [url=http://sinkfaucets.cf/art/sink-handle-leaking2/]Sink handle leaking[/url]
Mugosow
Some types of primary bone cancer are osteosarcoma, Ewing sarcoma, malignant fibrous histiocytoma and chondrosarcoma. If you have primary bone cancer, [url=http://histiocytoma.cf/nintendo-2dsxl-vs-3dsxl-which-one-you-should-histiocytoma-buy]histiocytoma dog removal cost[/url]
UhooLart
Patients talk about dental implants in CityDent clinic. [url=http://dentures.denta.top/art/dentures-and-dental/]Dentures and dental[/url]
KarenTow
Jan 6, 2017 If youd like to see what this process looks like, check out my short video How To Having bedbugs in the house is not necessarily a sign of a dirty home. “Across the United States, bees, wasps, biting flies, ants, spiders and scorpions all The first step to getting the safe open is to identify the problem. [url=http://howtogetridofantsinhouse.ga/preventing-water-hammer-dft-inc-how-to-get-rid-of-small-ants-in-your-house]how to get rid of small ants in your house[/url]