ruby string concatenation (I think?) - ruby

I'm just starting with "The Well-Grounded Rubyist", and they gave the following example:
print "Hello. Please enter a Celsius value: "
print "The Fahrenheit equivalent is ", gets.to_i * 9 / 5 + 32, ".\n"
In particular, I'm looking at line 2, where they seem to be using commas for string concatenation. I assume the + symbol isn't being used because of the + 32 portion of the code. However, can someone explain to me what the commas actually are doing?

The commas are argument separators. The print method can take any number of arguments and will print them in sequence. Any string concatenation (if any occurs here) would take place inside the print method itself.

The commas are delimiting the arguments to the print function.

Argument separators, i.e. print is called with three arguments.

Related

In TI-BASIC, how do I add a variable in the middle of a String?

I am wondering how to make something where if X=5 and Y=2, then have it output something like
Hello 2 World 5.
In Java I would do
String a = "Hello " + Y + " World " + X;
System.out.println(a);
So how would I do that in TI-BASIC?
You have two issues to work out, concatenating strings and converting integers to a string representation.
String concatenation is very straightforward and utilizes the + operator. In your example:
"Hello " + "World"
Will yield the string "Hello World'.
Converting numbers to strings is not as easy in TI-BASIC, but a method for doing so compatible with the TI-83+/84+ series is available here. The following code and explanation are quoted from the linked page:
:"?
:For(X,1,1+log(N
:sub("0123456789",ipart(10fpart(N10^(-X)))+1,1)+Ans
:End
:sub(Ans,1,length(Ans)-1?Str1
With our number stored in N, we loop through each digit of N and store
the numeric character to our string that is at the matching position
in our substring. You access the individual digit in the number by
using iPart(10fPart(A/10^(X, and then locate where it is in the string
"0123456789". The reason you need to add 1 is so that it works with
the 0 digit.
In order to construct a string with all of the digits of the number, we first create a dummy string. This is what the "? is used
for. Each time through the For( loop, we concatenate the string from
before (which is still stored in the Ans variable) to the next numeric
character that is found in N. Using Ans allows us to not have to use
another string variable, since Ans can act like a string and it gets
updated accordingly, and Ans is also faster than a string variable.
By the time we are done with the For( loop, all of our numeric characters are put together in Ans. However, because we stored a dummy
character to the string initially, we now need to remove it, which we
do by getting the substring from the first character to the second to
last character of the string. Finally, we store the string to a more
permanent variable (in this case, Str1) for future use.
Once converted to a string, you can simply use the + operator to concatenate your string literals with the converted number strings.
You should also take a look at a similar Stack Overflow question which addresses a similar issue.
For this issue you can use the toString( function which was introduced in version 5.2.0. This function translates a number to a string which you can use to display numbers and strings together easily. It would end up like this:
Disp "Hello "+toString(Y)+" World "+toString(X)
If you know the length of "Hello" and "World," then you can simply use Output() because Disp creates a new line after every statement.

Numbers vs string/expressions vs values

When I type the following:
print "2+2 is equal to" +2+2
I get an error message saying I can't convert a number into a string, but when I type:
print "2+2 is equal to", 2+2
it's accepting it and displays:
2+2 is equal to4
What's the difference between the two? It's not making logical sense to me. Could someone please explain it?
print "2+2 is equal to" + 2 + 2
Here you're trying to add a number to a string. This operation doesn't make sense. It's like adding an apple to a cat. The addition fails, but if it were to succeed, then print would print the result.
print "2+2 is equal to", 2 + 2
Here you're telling the print command to print this string and also result of summing these two numbers. it knows how to print strings and how to print numbers. Strings and numbers don't have to be mixed together in this case, they are handled separately. That's why this operation succeeds.
You can make the first operation work too. For this, you must be explicit that you want this number as a string, so that both addition operands are strings and can be actually added together.
print "2+2 is equal to" + (2 + 2).to_s
or
print "2+2 is equal to #{2 + 2}" # this is called string interpolation
Some languages try to be friendly and, if you're adding a number to a string, will stringify the number for you. Results can be... surprising.
Javascript:
"2 + 2 equals to " + 2 + 2
# => "2 + 2 equals to 22"
"2 + 2 equals to " + (2 + 2)
# => "2 + 2 equals to 4"
It's good that ruby doesn't do this kind of tricks :)
Everybody's pointed out how print works, so i thought i'd shed a bit of light on +.
These two operators look the same, right?
'2'+'2'
2+2
In actual fact, there are two very different operations happening:
String#+ - This concatenates the argument to the source string. Argument must be a string.
Fixnum#+ - This adds the argument to the source number. Argument must be a number.
So if String#+ only works on string objects, how is it that we can print different types of objects?
Some classes are very 'string-like' and can be treated as strings in most contexts (eg. Exception before Ruby 1.9) as they implement to_str(implicit conversion).
We can also implement to_s in our own objects to allow it to return a String representation of the object (explicit conversion).
You can read more about this at http://codeloveandboards.com/blog/2014/03/18/explicit-vs-implicit-conversion-methods/
print "2+2 is equal to" +2+2
is equivalent to:
print("2+2 is equal to" +2+2)
You are trying to add an integer 2 to a string "2+2 is equal to".
print "2+2 is equal to", 2+2
is equivalent to:
print("2+2 is equal to", 2+2)
Here print takes two arguemnts, one is a string, the other is an expression 2+2.
print "2+2 is equal to" + 2+2
fails because it tries to add a integer to a string before the result is send to print. An operation that does not make sense. Whereas:
print "2+2 is equal to", 2+2
is a other operation. Here you send two argument to print. A string and an integer. Internally print calls to_s on both values.
From the documentation:
print(obj, ...) → nil
Prints each object in turn to $stdout. [...] Objects that aren't strings will be converted by calling their to_s method.
Another way to do this is string interpolation, that also calls to_s automatically:
print "2+2 is equal to #{2+2}"

Ruby regex to capture any string with a number

I am looking for a regular expression in Ruby to capture a sentence that has any sort of number in it.
For instance, I need to capture all of the following:
"5 different ways to do it"
"2 x 2 is certainly 4"
"there are 15 different things"
"Try to get to 10"
I only want to capture sentences with a number within, but that has nothing else before or after the number. I don't want to include things like:
"$2 billion dollars"
"The 5x effect"
It has to be just a sequence for 1 or more numbers at the beginning, middle, or end of a sentence.
Thanks.
You probably want something like:
/^.*(?<!\S)\d+(?!\S).*$/
Which will match a number and "look-around" for a non-space.
This
(s =~ /(^|\s)\d+(\s|$)/) ? s : nil
will return the string s if it contains at least one non-negative integer, that is:
the entire string,
at the beginning of the string followed by a whitespace character,
at the end the string preceded by a whitespace character, or
is both preceded and followed by a whitespace character.

Ruby: Difference between these two?

I was wondering what the difference between print x and print "#{x}", in Ruby was. Does it really matter which one we use?
The expression print "#{foo}" roughly translates to print foo.to_s.
Kernel#print is a thin wrapper around IO#print which ultimatively calls IO#write. From write's documentation:
[...] If the argument is not a string, it will be converted to a string using to_s. [...]
So in the end, there is close to no difference. print "#{foo}" will however first create a String representation of foo and secondly interpolate that result into an otherwise empty string—but I think that could (should) easily be optimized by the interpreter.
print "#{foo}" - here you are doing string interpolation.Whatever object will be referenced by foo(if it is a local variable), returned from foo(if it is a method), on that result String#to_s will be applied.
print foo will output the object will be referenced by foo(if it is a local variable), returned from foo(if it is a method), on that result #to_s will be applied.
There is no difference, they both apply to_s implicitly at some point. You should use print x and not print "#{x}". Why would you wonder which to use? print "#{x}" is obviously less simple than print x.
The print name is usually used if you only need to print that thing and nothing more.
String interpolation is used when you want to insert the values in other strings.
print "My name is #{my_name} and I am currently #{my_age} years old."
It is even possible to insert some logic:
print "My name is #{my_name.capitalize} and"
print "I am currently #{my_age} year#{my_age>1 ? 's':''} old." #print years instead of year if age is greater than 1.

Why doesn't this Ruby replace regex work as expected?

Consider the following string which is a C fragment in a file:
strcat(errbuf,errbuftemp);
I want to replace errbuf (but not errbuftemp) with the prefix G-> plus errbuf. To do that successfully, I check the character after and the character before errbuf to see if it's in a list of approved characters and then I perform the replace.
I created the following Ruby file:
line = " strcat(errbuf,errbuftemp);"
item = "errbuf"
puts line.gsub(/([ \t\n\r(),\[\]]{1})#{item}([ \t\n\r(),\[\]]{1})/, "#{$1}G\->#{item}#{$2}")
Expected result:
strcat(G->errbuf,errbuftemp);
Actual result
strcatG->errbuferrbuftemp);
Basically, the matched characters before and after errbuf are not reinserted back with the replace expression.
Anyone can point out what I'm doing wrong?
Because you must use syntax gsub(/.../){"...#{$1}...#{$2}..."} or gsub(/.../,'...\1...\2...').
Here was the same problem: werid, same expression yield different value when excuting two times in irb
The problem is that the variable $1 is interpolated into the argument string before gsub is run, meaning that the previous value of $1 is what the symbol gets replaced with. You can replace the second argument with '\1 ?' to get the intended effect. (Chuck)
I think part of the problem is the use of gsub() instead of sub().
Here's two alternates:
str = 'strcat(errbuf,errbuftemp);'
str.sub(/\w+,/) { |s| 'G->' + s } # => "strcat(G->errbuf,errbuftemp);"
str.sub(/\((\w+)\b/, '(G->\1') # => "strcat(G->errbuf,errbuftemp);"

Resources