Ruby Splatted Array - ruby

Create a method called introduction that accepts a person's age, gender and any number of names, then returns a String that introduces that person by combining all of these values to create a message acceptable to the tests.
def introduction(age, gender, *names)
"Meet #{names.join(' ')}, who's #{age} and #{gender}"
end
For the .join method. Why do I need to add a string with a space (' ')?
Thanks in advance

The documentation of Ruby's Array#join method can be found here:
http://ruby-doc.org/core/Array.html#method-i-join
The string ' ' is a string with a single space in it. That string is supplied as the separator argument to Array#join. If you left out that argument, then the names would not have any spaces between them, and it would look bad:
Meet DavidGrayson, who's 123 and male.
But if you include the space, it should look like this:
Meet David Grayson, who's 123 and male.
You should be able to answer a question like that yourself by running the code in IRB or some other Ruby environment and seeing how it behaves. Experimentation is a great way to start understanding something.

Related

Ruby beginner i'm a little confused [duplicate]

This question already has answers here:
Why are exclamation marks used in Ruby methods?
(12 answers)
Closed 6 years ago.
I would like to know what the difference is between these two examples:
my_name = gets.chomp
my_name.capitalize
and
my_name = gets.chomp
my_name.capitalize!
The difference is
my_name.capitalize
returns a capitalized version of my_name without affecting the object my_name points to, while
my_name.capitalize!
still returns a capitalized version of my_name but my_name is changed too, so
my_name = "john"
puts my_name.capitalize # print 'John' but the value of my_name is 'john'
puts my_name.capitalize! # print 'John' and now the value of my_name is 'John'
From the Ruby capitalize docs:
capitalize
Returns a copy of str with the first character converted to uppercase
and the remainder to lowercase.
capitalize!
Modifies str by converting the first character to uppercase and the
remainder to lowercase. Returns nil if no changes are made.
I'm always so happy to see somebody getting into ruby!
The thing with ruby is that, even though it's a very friendly language, it assumes a lot of things without necessarily telling the newbies about it. They make lots of sense once you have a couple months under the belt with the language, but not before, so I understand your question.
First of all, the bang (!) is just part of the name itself. Ruby allows exclamation points and question marks as part of the method name just as any other character. Cool, right?
Why do people bother, though? Well, it's a convention. As a rule of thumb, an accepted explanation of why a method should have a bang sign is that the method does an invasive, destructive or mutating thing, that is, it destroys data, runs a transaction on the database, permanently changes data, etc.
It's not obligatory to name these kinds of methods like this, but it's a convention that's very well withheld in the Ruby community.
Programming Ruby says:
Methods that are "dangerous," or modify the receiver, might be named
with a trailing "!".
Hope this answers your question.

What does <<DESC mean in ruby?

I am learning Ruby, and in the book I use, there is an example code like this
#...
restaurant = Restaurant.new
restaurant.name = "Mediterrano"
restaurant.description = <<DESC
One of the best Italian restaurants in the Kings Cross area,
Mediterraneo will never leave you disappointed
DESC
#...
Can someone explain to me what <<DESC means in the above example? How does it differ from the common string double quote?
It is used to create multiline strings. Basically, '<< DESC' tells ruby to consider everything that follows until the next 'DESC' keyword. 'DESC' is not mandatory, as it can be replaced with anything else.
a = <<STRING
Here
is
a
multiline
string
STRING
The << operator is followed by an identifier that marks the end of the document. The end mark is called the terminator. The lines of text prior to the terminator are joined together, including the newlines and any other whitespace.
http://en.wikibooks.org/wiki/Ruby_Programming/Here_documents
It allows the creation of multi-line string constants in a readable way. See http://en.wikibooks.org/wiki/Ruby_Programming/Here_documents.
It is called a heredoc, or heredocument. It allows you to write multiline. You can test it in your terminal!

Replacing manually written date with a string containing it

I have these 2 things I am working with:
CSV.foreach('datafile.csv','r') {|row| D_Location << row[0]}
puts Date.new(2003,05,02).cwday
In the first line I would like to change the datafile.csv to something like a string so I can change one string and it changes for all of these codes. I have many, each controlling 1 csv column.
In the second one I would like to replace the actual date written, and replace it with a string. This is so that can be automatic, because the string will be generated based on other criteria.
I trust the mods will ban me if I'm being too much of a noob hehe. Then I'll toughen up and find these answers myself eventually. But so far I've solved a lot, but not this. Thanks in advance!
Make a function which takes in a string representing a weekday, and returns a number. Call this function later in your code:
Date.new(2003, 05, yourfun('Tuesday')).cwday
For the first part of your question, you're already working with a string. I think what you mean is that you want it to be in a variable:
csv_file = 'datafile.csv'
CSV.foreach(csv_file,'r') {|row| D_Location << row[0]}
For the second part of your question, Date.parse() works with strings, but they need to be in a format that it can recognize. If your date strings use commas, you can replace them with hyphens:
date_str = "2003,05,02"
Date.parse(date_str.gsub(",", "-")).cwday # => 5
It's not clear where your date strings will be coming from or what format they'll be in, but the general concepts you need to understand are that you can use variables, and that you can transform strings.

How to use ':' to break out words in %w'dog:cat:bird' w/o split

I am trying to do %w'dog:cat:bird' but I want the character that breaks apart the words to be a : rather than whitespace as %w currently does.
I do not want to use .split as in the actual code I am using a few different % idioms for different needs and I would like to use just one syntax.
I just checked in "The Ruby Programming Language" by Matz and David Flanagan, and it appears that array literals created with %w must use spaces to delimit the elements. If you really want to have arrays of strings, delimited by ":", and you don't want to use "split" in the code, I suggest you define a method of your own which will allow you to simulate the desired behavior, maybe something like:
class Object
def w(str)
str.split(":")
end
end
Then you can write something like:
w'a:b:c'

how to convert strings like "this is an example" to "this-is-an-example" under ruby

How do I convert strings like "this is an example" to "this-is-an-example" under ruby?
The simplest version:
"this is an example".tr(" ", "-")
#=> "this-is-an-example"
You could also do something like this, which is slightly more robust and easier to extend by updating the regular expression:
"this is an example".gsub(/\s+/, "-")
#=> "this-is-an-example"
The above will replace all chunks of white space (any combination of multiple spaces, tabs, newlines) to a single dash.
See the String class reference for more details about the methods that can be used to manipulate strings in Ruby.
If you are trying to generate a string that can be used in a URL, you should also consider stripping other non-alphanumeric characters (especially the ones that have special meaning in URLs), or replacing them with an alphanumeric equivalent (example, as suggested by Rob Cameron in his answer).
If you are trying to make something that is a good URL slug, there are lots of ways to do it.
Generally, you want to remove everything that is not a letter or number, and then replace all whitespace characters with dashes.
So:
s = "this is an 'example'"
s = s.gsub(/\W+/, ' ').strip
s = s.gsub(/\s+/,'-')
At the end s will equal "this-is-an-example"
I used the source code from a ruby testing library called contest to get this particular way to do it.
If you're using Rails take a look at parameterize(), it does exactly what you're looking for:
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367
foo = "Hello, world!"
foo.parameterize => 'hello-world'

Resources