This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the colon operator in Ruby?
While learning Ruby I've come across the ":" operator on occasion. Usually I see it in the form of
:symbol => value
what does it mean?
It just indicates a that it is a symbol instead of a string. In ruby, it is common to use symbols instead of strings.
{:foo => value}
{'foo' => value}
It's basically a short-hand way of expressing a string. It can not contain spaces as you can imagine so symbols usually use underscores.
Try this on your own:
foo = :bar
foo.to_s # means to string
baz = 'goo'
baz.to_sym # means to symbol
Related
This question already has answers here:
Why do two strings separated by space concatenate in Ruby?
(2 answers)
Closed 8 years ago.
How the following line of code concatenates a string in ruby?
2.1.0 :052 > value = "Kamesh" "Waran"
=> "KameshWaran"
I understand that '+' is a method on String class which concatenates the strings passed. How the space(' ') can be the operator/method?
Can anyone elaborate how the space(' ') concatenate strings?
The space is not an operator. This only works for string literals, and is just part of the literal syntax, like the double-quotes. If you have two string literals with nothing but whitespace between them, they get turned into a single string. It's a convention borrowed from later versions of C.
irb(main):001:0> foobar = "foo" "bar"
=> "foobar"
irb(main):002:0> foo="foo"
=> "foo"
irb(main):003:0> bar="bar"
=> "bar"
irb(main):004:0> foo bar
NoMethodError: undefined method `foo' for main:Object
from (irb):4
from /usr/local/var/rbenv/versions/2.1.3/bin/irb:11:in `<main>'
irb(main):005:0>
If you do a search on this site you get an answer.
Found on :
Why do two strings separated by space concatenate in Ruby?
Implementation details can be found in parse.y file in Ruby source
code. Specifically, here.
A Ruby string is either a tCHAR (e.g. ?q), a string1 (e.g. "q", 'q',
or %q{q}), or a recursive definition of the concatenation of string1
and string itself, which results in string expressions like "foo"
"bar", 'foo' "bar" or ?f "oo" 'bar' being concatenated.
This question already has answers here:
Are strings in Ruby mutable? [duplicate]
(6 answers)
Closed 8 years ago.
How come concatenating to a string does not change its object_id? My understand was that Strings are immutable because Strings are essentally Arrays of Characters, and Arrays cannot be changed in memory since they are contiguous. Yet, as demonstrated below: Instantiating a String than adding characters does not change it's object_id. How does concatenation effect the String in memory?
2.1.2 :131 > t1 = "Hello "
=> "Hello "
2.1.2 :132 > t1.object_id
=> 70282949828720
2.1.2 :133 > t2 = t1
=> "Hello "
2.1.2 :134 > t2.object_id
=> 70282949828720
2.1.2 :135 > t2 << "HEY THERE MATE"
=> "Hello HEY THERE MATE"
2.1.2 :136 > t2.object_id
=> 70282949828720
2.1.2 :137 > t1.object_id
=> 70282949828720
2.1.2 :138 >
How come concatenating to a string does not change its object_id?
Because it's still the same string it was before.
My understand was that Strings are immutable
No, they are not immutable. In Ruby, strings are mutable.
because Strings are essentally Arrays of Characters,
They are not. In Ruby, strings are mostly a factory for iterators (each_line, each_char, each_codepoint, each_byte). It implements a subset of the Array protocol, but that does not mean that it is an array.
and Arrays cannot be changed in memory since they are contiguous.
Wrong, arrays are mutable in Ruby.
Yet, as demonstrated below: Instantiating a String than adding characters does not change it's object_id. How does concatenation effect the String in memory?
The Ruby Language Specification does not prescribe any particular in-memory representation of strings. Any representation is fine, as long as it supports the semantics specified in the Ruby Language Specification.
Here's a couple of examples from some Ruby implementations:
Rubinius:
kernel/common/string.rb
kernel/bootstrap/string.rb
vm/builtin/string.cpp
Topaz:
topaz/objects/stringobject.py
Cardinal:
src/classes/String.pir
IronRuby:
Ruby/Builtins/MutableString.cs
JRuby:
core/src/main/java/org/jruby/RubyString.java
Ruby strings are not immutable, in contrast to languages like Python and Java. The underlying char array is internally resized to accommodate the appended characters.
If you want an immutable string in ruby (for example, Bad Things can happen if you use a mutable value as a hash key), use a symbol:
my_sym = :foo
or
my_sym = my_string.to_sym
This question already has answers here:
What does the !~ method do with String in Ruby
(2 answers)
Closed 8 years ago.
When declaring syntax such as:
a !~ b
where a,b are variables, what does it mean?
It is negation of =~, a regex match.
"a" !~ /b/
# => true
It is useful when you want to check whether a string does not match a certain pattern. For example, if you want to check if string s includes only numbers, then you can do:
s !~ /\D/
This question already has an answer here:
Why does string interpolation work in Ruby when there are no curly braces?
(1 answer)
Closed 8 years ago.
Please observe the following:
"abcd#fg" # => "abcd#fg"
"abcd#$fg" # => "abcd" characters #$ and after them are skipped
"abcd##fg" # => "abcd" characters ## and after them are skipped
It could be string interpolation just with # instead of #{}.
$fg = 8
"abcd#$fg" # => "abcd8"
#fg = 6
"abcd##fg" # => "abcd6"
It works like interpolation. Is it a bug or a feature?
You can actually interpolate global, instance, and class variables omitting the braces:
$world = 'world'
puts "hello, #$world"
# hello, world
In your example both $fg and #fg are uninitialized and thus evaluated to nil, that's why they are intorpolated as empty strings. When you write "abcd#fg" nothing is interpolated because the # is not followed by one of {, #, $.
You can find the feature documented in the RubySpec (thanks to #DavidMiani).
If you ask me, don't rely on this behaviour and always interpolate variables using braces, both for readability and to avoid problems such:
#variable = 'foo'
puts "##variable_bar"
This will output an empty string instead of the, probably, expected string "foo_bar", because it is trying to interpolate the undefined instance variable #variable_bar.
This question already has answers here:
How to compare strings ignoring the case
(5 answers)
Closed 7 years ago.
I want to test 2 strings for equality in Ruby in a case insensitive manner.
In languages, such as Fantom, you simply write:
string1.equalsIgnoreCase(string2)
What's the idiomatic way to do this in Ruby?
You can use casecmp
"Test".casecmp("teST")
=> 0
"Test".casecmp("teST2")
=> -1
So to test for equality, you can do:
if str.casecmp(str2).zero?
# strings are equal
end
Though there is casecmp:
0 == s1.casecmp(s2) # strings equal
I personally prefer
s1.downcase == s2.downcase
You can convert the strings to lowercase and then compare
a.downcase == b.downcase
Or, if you prefer, to uppercase
a.upcase == b.upcase
You can use String#match method :
s = "Test"
s.match(/teST/i) # => #<MatchData "Test">
s.match(/teST2/i) # => nil
Remember in Ruby all objects are has the truth value, except nil and false. So you can use this trick also to perform conditional testing.